2
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;”这一行,它运行良好。到底是怎么回事?只能将不可变数组推到其他数组上吗?

4

1 回答 1

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],
)
于 2013-04-05T07:21:27.660 回答