在Perl中,如何使用字符串作为变量名?

Luc*_*uci 7 string variables perl

可能重复:
如何在Perl中将变量用作变量名?

这可行吗?我需要将字符串更改为变量.

例:

如果我有这样的变量:

$this_is_test = "what ever";
$default = "this";
$default = $default . "_is_test";
Run Code Online (Sandbox Code Playgroud)

我想要$default的价值$this_is_test.

Sin*_*nür 13

根据我的另一个答案,每当您发现自己将字符串后缀添加到变量名称时,请使用哈希:

my %this = (
    is_test => "whatever",
    is_real => "whereever",
);

my $default = $this{is_test};

print "$default\n";
Run Code Online (Sandbox Code Playgroud)

千万不要使用符号引用用于此目的,因为他们没有必要,也有可能在你的问题的情况下是非常有害的.有关更多信息,请参阅"将变量用作变量名称"为何愚蠢?,第2部分第3部分mjd.


Cha*_*ens 5

正如rafl所说,这可以通过符号引用来实现,但是它们非常危险(它们是代码注入向量),并且不能与词法变量一起使用(并且应该使用词法变量而不是包变量)。每当您认为想要符号引用时,几乎可以肯定要使用散列。而不是说:

#$this_is_test is really $main::this_is_test and is accessible from anywhere
#including other packages if they use the $main::this_is_test form 
our $this_is_test = "what ever";
my $default       = "this";
$default          = ${ $default . "_is_test" };
Run Code Online (Sandbox Code Playgroud)

你可以说:

my %user_vars = ( this_is_test => "what ever" );
my $default   = "this";
$default      = $user_vars{ $default . "_is_test" };
Run Code Online (Sandbox Code Playgroud)

这将其范围限制为%user_vars在其中创建该块的范围,并且密钥与实际变量的隔离限制了注入攻击的危险。