如何在Perl中使用变量作为变量名? [英] How can I use a variable as a variable name in Perl?

查看:1158
本文介绍了如何在Perl中使用变量作为变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在perl中实现以下目标

I need to achieve the following in perl

printmsg(@val1, $msg1) if @val1;
printmsg(@val2, $msg2) if @val2;
printmsg(@val3, $msg3) if @val3;
printmsg(@val4, $msg4) if @val4;
printmsg(@val5, $msg5) if @val5;
printmsg(@val6, $msg6) if @val6;

所以我写了以下代码段

for(my $i=1; $i < 6; $i++ ) {
    printmsg(@val$i, $msg$i) if @val$i;
}

它不起作用,并因错误而中断.

It doesn't work and breaks out with errors.

推荐答案

只要您发现自己用整数索引对变量名进行后缀,意识到您应该改用数组:

Whenever you find yourself postfixing variable names with an integer index, realize that you should have used an array instead:

my @msgs = ('msg1', 'msg2', ..., 'msg6');
my @vals = ( [ @val1 ], [ @val2 ], ..., [ @val6 ] );

另请参阅常见问题解答如何使用变量作为变量名?

See also the FAQ How can I use a variable as a variable name?

作为常见问题解答的答案,如果变量不是由整数索引的,则可以使用哈希表:

As the answer to the FAQ notes, if the variables are not indexed by an integer, you can use a hash table:

通过使用符号引用,您只是在使用程序包的符号表哈希(例如%main::),而不是用户定义的哈希.解决方案是改用您自己的哈希或真实引用.

By using symbolic references, you are just using the package's symbol-table hash (like %main::) instead of a user-defined hash. The solution is to use your own hash or a real reference instead.

$USER_VARS{"fred"} = 23;
my $varname = "fred";
$USER_VARS{$varname}++;  # not $$varname++

您应该每年至少阅读一次完整的FAQ列表.

You should read the entire FAQ list at least once a year.

更新:我故意将符号引用排除在我的回答之外,因为这些符号引用是不必要的,在您的问题中可能非常有害.有关更多信息,请参见为什么将变量用作变量名"是愚蠢的?第2部分第3部分,由 mjd .

Update: I purposefully left symbolic references out of my answer because they are unnecessary and likely very harmful in the context of your question. For more information, see Why it's stupid to 'use a variable as a variable name'?, part 2 and part 3 by mjd.

这篇关于如何在Perl中使用变量作为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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