blu*_*695 1 arrays perl reference
我想创建一个2d数组(@combinations),它包含另一个数组(@indices)的所有组合.
我正在使用push附加另一个数组(@temp2)的引用.当我打印我的2d数组(使用Dumper)时,它并不像我预期的那样:print循环内的语句显示每个推送的引用都是非空列表,但最终我的所有引用都指向一个空列表.为什么?
use Math::Combinatorics;
use Data::Dumper;
my (@combinations, @temp2);
my @indices = (0, 2, 4);
my $count = 1;
my $counter = @indices;
while ($counter>= $count) {
my $c = Math::Combinatorics->new(
count => $count,
data => \@indices,
);
$count++;
while (@temp2 = $c->next_combination) {
print "@temp2 \n";
push @combinations, \@temp2;
}
}
print Dumper(\@combinations);
Run Code Online (Sandbox Code Playgroud)
因为您@temp2在顶层声明,所以引用\@temp2将始终指向相同的数据.因为一旦为@temp2空就退出循环,所有引用@combinations将指向同一个空数组.
补救很容易:通过写入声明循环的@temp2本地while
while (my @temp2 = $c->next_combination) {
Run Code Online (Sandbox Code Playgroud)
每次重复循环时,这将创建一个具有自己引用的新变量@temp2.