在Perl中向数组添加元素 [英] Adding elements to an array in Perl
问题描述
我在此代码中要添加10、11和12到数组arr。
I have this code where I want to add 10, 11 and 12 to array arr.
my @num=(0,1,2);
my $i=10;
for my $d (@num){
if (defined($d)) {
my @arr;
$arr[$d] = $i;
$i=$i+1;
my $dvv=dump(\@arr);
print "**** $dvv \n";
}
}
输出为:
**** [10]
**** [undef, 11]
**** [undef, undef, 12]
为什么仅定义数组的最后一个元素?
Why is only the last element of array defined?
推荐答案
由于您已在循环中声明了数组,因此每次都会重新创建该数组,并删除先前迭代中放置在数组中的所有值
Since you have the declaration of the array within the loop, it will re-create it each time, removing any values that would have been placed in it on previous iterations of the loop.
如果希望保留值,则应在循环之前取消 @arr
的操作:
You should declaure @arr
before the loop if you want the values to stay:
my @arr;
for my $d (@num) {
...
}
由于这一行:
$arr[$d];
$ d
是由其他数组(0,然后1,然后2)。因此,它将 $ i
的值放在数组的该位置,并将之前的值放入 undef
。
$d
is the position defined by the other array (0, then 1, then 2). So it puts the value of $i
in that position in the array, and puts values before to undef
.
这篇关于在Perl中向数组添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!