变量名中的 perl 变量替换 [英] perl variable substitution in variable name

查看:55
本文介绍了变量名中的 perl 变量替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/perl
my $var_a;
$sub_a = "a";
$var_a = "a";
print ${var_."$sub_a"},"\n";


$sub_b = "b";
$var_b = "b";
print ${var_."$sub_b"},"\n";

__DATA__

b

为什么打印的是 b 而不是 a?这对我来说似乎是非常意外的行为.

Why is b printed, but not a? This seems like very unexpected behaviour to me.

我正在尝试使用带有替换名称的变量.在实践中,我不能只是不声明变量,因为赋值是在 forloop 中完成的,因此具有不同的词法范围.

I'm trying to use a variable with a substituted name. In practice, I cannot just not declare the variable, since the assignment is being done in a forloop and thus has different lexical scope.

推荐答案

请注意,这与您使用变量来包含其他变量的名称这一事实无关.

Please note that this has NOTHING to do with the fact that you are using variables to contain the name of other variable.

这不起作用的原因是因为 ${"var_a"} 构造实际上是指包级变量 $main::var_a.

The reason this doesn't work is because ${"var_a"} construct in reality refers to a package level variable $main::var_a.

由于 $var_a 被声明为词法变量,它是一个不同的标识符,因此 ${"var_a"} 是 undef.

Since $var_a is declared as a lexical variable, it's a DIFFERENT identifyer, and therefore ${"var_a"} is undef.

你可以看到,如果你把 my $var_a 改为 our $var_a

You can see that if you change my $var_a to our $var_a

our $var_a="a";
my $var_b="b";
$var_c="c";

print ${"var_a"},"\n";
print ${"var_b"},"\n";
print ${"var_c"},"\n";

######## RESULTS:
a

c

正如其他人所指出的,虽然有一个很好的解释为什么您尝试做的事情不起作用,但您正在做的事情很可能是错误的方法.除非没有更好的方法,否则您几乎不应该使用这种方法;如果没有您的问题,尚不清楚更好的方法是什么,但很可能是像 TLP 的答案所说的哈希.

As others noted, while there is a good explanation for why what you are trying to do doesn't work, WHAT you are doing is likely the wrong approach. You should almost NEVER use this method unless there's no better way; without your problem it's not clear what the better way is but most likely would be a hash like TLP's answer says.

这篇关于变量名中的 perl 变量替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆