简体   繁体   English

如何在Perl中使用变量作为变量名?

[英]How can I use a variable as a variable name in Perl?

I need to achieve the following in perl 我需要在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;

So i wrote the following snippet 所以我写了以下片段

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: 作为常见问题解答的答案,如果变量不是用整数索引的,则可以使用哈希表:

By using symbolic references, you are just using the package's symbol-table hash (like %main:: ) instead of a user-defined hash. 通过使用符号引用,您仅使用包的符号表哈希(例如%main::而不是用户定义的哈希。 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++ 

You should read the entire FAQ list at least once a year. 您应该至少每年一次阅读整个FAQ列表。

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 . 第2部分第3部分 ,作者: mjd

You can't just string variables together like that and get a resulting variable. 您不能只是像这样将变量串在一起并得到结果变量。 You COULD evaluate the expression of $msg + i , but it's probably better if you make msg an array and just index: $msg[$i] . 您可以评估$msg + i的表达式,但是如果将msg制成数组并仅索引: $msg[$i]可能会更好。

If I understand, you need "eval"! 据我了解,您需要“评估”!

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

But remember! 但要记住! All variable(@val1, @val2, ..., @valN) must exists! 所有变量(@ val1,@ val2,...,@ valN)必须存在! As you're not providing too much of your code I'm unavaiable to infer more about this problem. 由于您没有提供太多代码,因此无法推断出更多有关此问题的信息。 Maybe you could provide more code huh? 也许您可以提供更多代码吧?

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

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