【发布时间】:2020-03-31 06:11:11
【问题描述】:
以下代码:
use strict;
use warnings;
my @array = (0,1,2,3,4,5,6,7,8,9);
print "array ref is ".\@array."\n";
my @copy_refs;
for my $element(@array) {
my @copy = @array;
print "copy ref is ".\@copy."\n";
push @copy_refs, \@copy;
}
如人们所料,产生以下输出:
array ref is ARRAY(0x21ae640)
copy ref is ARRAY(0x21e2a00)
copy ref is ARRAY(0x21d7368)
copy ref is ARRAY(0x21d71e8)
copy ref is ARRAY(0x21d70c8)
copy ref is ARRAY(0x21d6fa8)
copy ref is ARRAY(0x21d6e88)
copy ref is ARRAY(0x21d6d68)
copy ref is ARRAY(0x21d6c48)
copy ref is ARRAY(0x21cf8a0)
copy ref is ARRAY(0x21cf780)
但是,删除push @copy_refs, \@copy; 的相同代码会产生以下输出:
array ref is ARRAY(0x229e640)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
copy ref is ARRAY(0x22d2a00)
这是为什么?
【问题讨论】:
-
您的代码已经执行
push @copy_refs, \@copy;。你的意思是“相同的代码,push @copy_refs, \@array”? -
如果您不为每次迭代保存对
@copy的引用,它将在每次循环迭代时被销毁。因此,下一个数组@copy可能使用与前一个相同的内存地址 -
你的评论很有道理哈康。我认为这是正确的答案。