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

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

In fact, I want to make a kind of pointer to a global namespace or hash search in the global namespace.

Failed to complete the following:

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

It prints only a new line.

+1
perl
source share
3 answers

This trick only works with global variables (symbolic links look for the symbol table of the current package), i. e.

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

If you want to catch vocabulary, you will need 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 links (if you can).

+7
source share

There are so many examples in Perl where you should use symbolic links. Avoid symbolic links in all other cases not about style. It's about a smart programmer. As mjd explains in Why is it stupid to "use a variable as a variable name" :

The real root of the problem code is fragile. When you do this, you mix different things. And if two of them, unlike things, have the same name, they will collide, and you will get the wrong answer. Thus, you have a complete long list of names that you must be careful not to reuse, and if you mess up, you will get a very strange error. This is exactly the problem that the namespace was invented for the solution, and that it was this hash: the portable namespace.

See also Part 2 and Part 3 .

+4
source share

Without my and $$bar works for me:

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

You can learn more about using a variable as a variable name in the Perl Question List .

0
source share

All Articles