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

雨燕双飞 提交于 2019-12-02 07:16:32

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.

Aif

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!