给出以下数组:
#!/usr/local/bin/perl -w
use strict;
use warnings;
my $test1 = [['1005','bak','lah','blasck','reomhol'],
['1010','name','turd','furguson','reomhol'],
['1055','a','b','c','reomhol']];
my $test2 = [['1010','name','/home/roost/chicken.pm'],
['1010','name','/home/roost/chicken2.pm'],
['1010','name','/home/roost/chicken3.pm']];
my $match_array = [];
my $nomatch_arr = [];
我通过比较$ test1和$ test2创建了一个数组数组($ match_array)。如果$ test1中每个数组的第一个元素与$ test2中每个数组的第一个元素匹配,那么一个条目将被推送到$ match_array。因此,应该有3个重复的条目。然后,我同时单步执行$ test2和$ match_arr,尝试将唯一的“位置”推送到$ match_array中的每个数组中。
my $flag = 0;
#foreach my $i (@$test1)
#my $tot = @$test1;
#$tot -= 1;
foreach my $i ( @$test1 )
{
#print "line 25: $$i[0]\n\n\n";
my $test2scalar = @$test2;
for (my $j=0;$j<$test2scalar;$j++)
{
#print "line 29: $test2->[$j][0]\n";
if($$i[0] == $test2->[$j][0])
{
push(@$match_array,$i);
$flag += 1;
}
}
if ($flag == 0)
{
push(@$nomatch_arr,$i);
}
}
print "------------------------Initial Output----------------------------\n";
for (my $k=0;$k<@$match_array;$k++)
{
print "$k-->@{$match_array->[$k]}\n";
}
print "------------------------Begin Push----------------------------\n";
for (my $count=0;$count<@$test2;$count++)
{
print "$test2->[$count][2]\n";
print "$count => @{$match_array->[$count]}\n";
push(@{$match_array->[$count]}, $test2->[$count][2]);
}
print "------------------------Final Output----------------------------\n";
for (my $k=0;$k<@$match_array;$k++)
{
print "$k-->@{$match_array->[$k]}\n";
}
为什么当使用push(@{$match_array->[$count]}, $test2->[$count][2]);
时,它会将唯一位置推送到$ match_array的每个数组中?
输出:
------------------------Initial Output----------------------------
0-->1010 name turd furguson reomhol
1-->1010 name turd furguson reomhol
2-->1010 name turd furguson reomhol
------------------------Begin Push----------------------------
unique location: /home/roost/chicken.pm
array element: 0 => 1010 name turd furguson reomhol
unique location: /home/roost/chicken2.pm
array element: 1 => 1010 name turd furguson reomhol /home/roost/chicken.pm
unique location: /home/roost/chicken3.pm
array element: 2 => 1010 name turd furguson reomhol /home/roost/chicken.pm /home/roost/chicken2.pm
------------------------Final Output----------------------------
0-->1010 name turd furguson reomhol /home/roost/chicken.pm /home/roost/chicken2.pm /home/roost/chicken3.pm
1-->1010 name turd furguson reomhol /home/roost/chicken.pm /home/roost/chicken2.pm /home/roost/chicken3.pm
2-->1010 name turd furguson reomhol /home/roost/chicken.pm /home/roost/chicken2.pm /home/roost/chicken3.pm
答案 0 :(得分:0)
我只是想补充一下以帮助下一个人
此问题的一个易于复制的示例:
let foo = Array(3).fill([]) //creates an array with three empty arrays inside
foo[0].push('bar') //[['bar'],['bar'],['bar']]
对比
let foo = [[],[],[]] //creates an array with three empty arrays inside it
foo[0].push('bar') // [['bar'],[],[]]