开发者

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.


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).


There are very very very preciously few instances in Perl where you must use symbolic references. Avoiding symbolic references in all other instances is not about style. It is about being a smart programmer. As mjd explains in Why it's stupid to "use a variable as a variable name":

The real root of the problem code is: It's fragile. You're mingling unlike things when you do this. And if two of those unlike things happen to have the same name, they'll collide and you'll get the wrong answer. So you end up having a whole long list of names which you have to be careful not to reuse, and if you screw up, you get a very bizarre error. This is precisely the problem that namespaces were invented to solve, and that's just what a hash is: A portable namespace.

See also Part 2 and Part 3.


Without my and with $$bar works for me:

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

You can find out more about using a variable as a variable name in the Perl FAQ List.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜