use strict;
my @array = ();
my @nums = [3, 4];
foreach my $i ( 0 .. 10 ) {
foreach my $j ( 0 .. 10 ) {
$nums[0] = 4+1;
push @{ $array[$i] }, @nums;
}
}
print $array[6][2][0]. "\n";
正如可以看到他们是否运行代码,这不能正常运行。但是,如果你注释掉“$ nums [0] = 4 + 1;”这一行,它运行正常。到底是怎么回事?只能将不可变数组推送到其他数组吗?
答案 0 :(得分:5)
@nums
是一个数组,您可以指定一个数组引用(带括号[]
)。因此,将其更改为正确的数组声明:my @nums = (3, 4);
use strict;
use Data::Dump;
my @array = ();
my @nums = (3, 4);
foreach my $i ( 0 .. 10 ) {
foreach my $j ( 0 .. 10 ) {
$nums[0] = 4+1;
push @{ $array[$i] }, @nums;
}
}
dd @array;
#-- output:
(
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
[5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4],
)