perlsymbolic-references

How can I use the value of a variable as a variable name in Perl?


If I have a variable, $bar, which is equal to string "foo" and $foo is equal to 0xdead, how can I get $foo's value while I only have the the string for the variable name?

Essentially, I want to do a kind of pointer indirection on the global namespace or a hash lookup on the global namespace.

The following didn't work:

perl -e 'my $foo=0xdead; my $bar ="foo"; print ${$bar}."\n";' 

It only prints the newline.


Solution

  • This trick works only with global variables (symbolic references seek the symbol table of the current package), i. e.

    perl -e '$foo=0xdead; my $bar ="foo"; print ${$bar}."\n";' 
    

    If you want to catch lexicals, you'll have to use eval ""

    perl -e 'my $foo=0xdead; my $bar ="foo"; print eval("\$$bar"),"\n";' 
    

    But using eval "" without purpose is considered bad style in Perl, as well as using global variables. Consider using real references (if you can).