Arrays 如何在数组结构的数组中创建嵌套数组的副本
我正在尝试创建嵌套数组的副本,但似乎我继续尝试创建引用 更具体地说,我试图创建一个数组数组,其中每个子数组都构建在前面的数组的基础上。以下是我的尝试:Arrays 如何在数组结构的数组中创建嵌套数组的副本,arrays,perl,reference,shallow-copy,Arrays,Perl,Reference,Shallow Copy,我正在尝试创建嵌套数组的副本,但似乎我继续尝试创建引用 更具体地说,我试图创建一个数组数组,其中每个子数组都构建在前面的数组的基础上。以下是我的尝试: #!/usr/bin/perl -w use strict; use warnings; my @aoa=[(1)]; my $i = 2; foreach (@aoa){ my $temp = $_;#copy current array into $temp push $temp, $i++; push @aoa, $temp;
#!/usr/bin/perl -w
use strict;
use warnings;
my @aoa=[(1)];
my $i = 2;
foreach (@aoa){
my $temp = $_;#copy current array into $temp
push $temp, $i++;
push @aoa, $temp;
last if $_->[-1] == 5;
}
#print contents of @aoa
foreach my $row (@aoa){
foreach my $ele (@$row){
print "$ele ";
}
print "\n";
}
我的输出是:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
我希望/期望它是:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
我假设我的问题在于如何分配$temp,如果不是这样,请告诉我。非常感谢您的帮助。使用
my
创建一个新数组,复制要构建的数组的内容,然后添加到其中
使其尽可能靠近您的代码
foreach (@aoa) {
last if $_->[-1] == 5;
my @temp = @$_; #copy current array into @temp
push @temp, $i++;
push @aoa, \@temp;
}
使用
my
创建一个新数组,复制要构建的数组的内容,然后添加到其中
使其尽可能靠近您的代码
foreach (@aoa) {
last if $_->[-1] == 5;
my @temp = @$_; #copy current array into @temp
push @temp, $i++;
push @aoa, \@temp;
}
一般来说,您可以使用Storable的
dclone
。zdim的解决方案在这种情况下更合适(因为您只需要一个简单的浅拷贝)。zdim的解决方案在这种情况下更合适(因为您只需要一个简单的浅层副本)。或者,如果您想使用匿名数组,push@aoa,[@$\$i++]
@ikegami非常感谢您的编辑和评论,这会更好。或者如果您想使用匿名数组,push@aoa,[@$\u,$i++]
@ikegami非常感谢您的编辑和评论,这会更好。