简体   繁体   English

如何在Perl中将变量的值用作变量名?

[英]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? 如果我有一个变量$bar ,它等于字符串"foo"$foo等于0xdead ,当我只有变量名的字符串时,如何获得$foo的值?

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), ie 此技巧仅适用于全局变量(符号引用查找当前包的符号表 ),即

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

If you want to catch lexicals, you'll have to use eval "" 如果要捕捉词汇,则必须使用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. 但是在Perl中使用无目的eval ""和使用全局变量被认为是不好的样式。 Consider using real references (if you can). 考虑使用真实引用(如果可以)。

There are very very very preciously few instances in Perl where you must use symbolic references. 在Perl中,非常非常非常少的实例必须使用符号引用。 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" : 正如mjd在“ 为什么使用变量作为变量名”为什么这么愚蠢

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 . 另请参见第2 部分第3部分

Without my and with $$bar works for me: 没有my和有$$bar对我有效:

$ 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 . 您可以在Perl FAQ列表中找到有关使用变量作为变量名称的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM