Link to home
Start Free TrialLog in
Avatar of Troyh
Troyh

asked on

Making a scalar from a string.

I am implementing a look up table in Perl using Hashes and would like to make a string into a scalar in order to select the appropriate hash - confused? Check out the code below!

%RunTestIdle = (0,"Run-Test-Idle",1,"Select-DR-Scan");
%SelectDRScan = (0,"Capture-DR",1,"Select-IR-Scan");
%CaptureDR = (0,"Shift-DR",1,"Exit1-DR");

This program accesses a text file and pulls out several bits of information
$selector = $zeroOrOne;      #$zeroOrOne is obtained from the text file
$currentState = $array[0];   #$array[0] will be a string and will be equal to one of the hash names
                                          #Eg. $currentState = "SelectDRScan";

so based on the two variables above I would like to impliment the following which should return either "Capture-DR" or "Select-IR-Scan" based on the value of $selector.
$nextState = $currentState{$zeroOrOne};

However this wont work because perl will look for a Hash called %currentState. If I could force the $currentState string to a scalar of the same name it would work.

I could always implement an if statement to figure out which hash to select based on the $currentState but was wondernig if there is a simpler way of doing this.

Any comments or if anyone can suggest a better way to implement a look-up table let me know!

Thanks, - Troy
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
#or, you could declare
%nextState=(
RunTestIdle => {0,"Run-Test-Idle",1,"Select-DR-Scan"},
SelectDRScan => {0,"Capture-DR",1,"Select-IR-Scan"},
CaptureDR => {0,"Shift-DR",1,"Exit1-DR"},
);
#then do
$nextState = $nextState{$currentState}{$zeroOrOne};
Hi ozo,
> $nextState = $nextState{$currentState}{$zeroOrOne};

That's an elegant way for a state machine. Good one!

Cheers!

Stefan