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
Who is Participating?
ozoConnect With a Mentor Commented:
#or, you could declare
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!


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.