本文介绍了为什么不能使用Perl变量的值来访问词法变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么要打印42:
$answer = 42;
$variable = "answer";
print ${$variable} . "\n";
但这不是:
my $answer = 42;
my $variable = "answer";
print ${$variable} . "\n";
推荐答案
仅包变量(在第一个示例中声明的种类)可以通过符号引用作为目标.不能使用词法(my
)变量,这就是第二个示例失败的原因.
Only package variables (the kind declared in your first example) can be targeted via symbolic references. Lexical (my
) variables, cannot be, which is why your second example fails.
有关Perl中两个独立的变量系统的方式,请参见出色的文章应付范围操作.并请参见出色的为什么使用变量变量名是愚蠢的,为什么这很愚蠢. :)
See the excellent article Coping with Scoping for how the two separate variable systems in Perl operate. And see the also excellent Why it's stupid to use a variable variable name for why that's stupid. :)
这篇关于为什么不能使用Perl变量的值来访问词法变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!