简体   繁体   English

如何在Perl中使用索引名称创建新变量?

[英]How do I create new variables with indexed names in Perl?

hi i've read some related question non seems tohelp me. 您好,我读过一些相关的问题,似乎对我没有帮助。 this is a code that will explain what i want. 这是一个代码,将解释我想要什么。

for ($i=0;$i<5;$i++) {
  my $new$i=$i;
  print "\$new$i is $new$i";
}

expecting variables to be named $new0 , $new1 , $new2 , $new3 , $new4 , $new5 . 期望变量被命名为$new0$new1$new2$new3$new4$new5 and to have the abillty to use them in a loop like the print command is trying to do. 并有能力像print命令一样在循环中使用它们。 Thanks 谢谢

You want to use a hash or array instead. 您想改用哈希或数组 It allows a collection of data to remain together and will result in less pain down the line. 它可以使数据收集保持在一起,从而减少生产过程中的痛苦。

my %hash;
for my $i (0..4) {
    $hash{$i} = $i;
    print "\$hash{$i} is $hash{$i}\n";
}

Can you describe why exactly you need to do this. 您能描述为什么确实需要这样做吗? Mark Jason Dominus has written why doing this is not such a good idea in Why it's stupid to "use a variable as a variable name" part 1 , part 2 and part 3 . 马克·杰森·多米纳斯(Mark Jason Dominus)在第1 部分第2 部分第3 部分 “为什么将变量用作变量名”中很愚蠢,为什么这样做不是一个好主意。

If you think your need is an exception to cases described there, do let us know how and somebody here might help. 如果您认为自己的需求是此处所述案例的例外,请告诉我们如何做,这里的人可能会有所帮助。

You are asking a common question. 您在问一个常见问题。 The answer in 99.9% of cases is DON'T DO THAT . 在99.9%的情况下,答案是“ 不要做”

The question is so common that it is in perlfaq7: How can I use a variable as a variable name? 这个问题是如此普遍,以至于出现在perlfaq7中:如何使用变量作为变量名? .

See " How do I use symbolic references in Perl? " for lots of discussion of the issues with symbolic references. 有关符号引用问题的大量讨论,请参见“ 如何在Perl中使用符号引用? ”。

use a hash instead. 使用哈希代替。

my %h=();
$new="test";
for ($i=0;$i<5;$i++) {
  $h{"$new$i"}=$i;
}
while( my( $key, $value ) = each( %h ) ) {
    print "$key,$value\n";
}

if you want to create variables like $newN you can use eval : 如果要创建$ newN这样的变量,可以使用eval

eval("\$new$i=$i");

(using hash probably would be better) (使用哈希可能会更好)

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

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