【发布时间】:2015-06-18 17:55:45
【问题描述】:
以下示例展示了我正在努力解决的问题。
在玩具示例中,我有一个包含两个级别的数组 @actors。
我还有一组哈希 @people,我用它来“查找”@actors 中人员的属性。
程序的输出应该是:
blue, blue cat, cat
red, red dog, dog
blue, blue cat, cat
red, red dog, dog
但我得到的是:
blue, cat cat, cat
red, dog dog, dog
blue, cat cat, cat
red, dog dog, dog
也就是说,似乎在设置$favanim[$i][$j] 时,我似乎也覆盖了$favcols[$i][$j] 的值。
我怀疑由于某种原因@actors 是一个二维数组这一事实意味着通过= 的赋值是作为引用而不是作为值,尽管我不知道为什么或如何阻止它。
请帮忙!
玩具程序在这里:(如果它可以简化但仍然存在问题,我深表歉意 - 我花了大部分下午的时间才把它精简到这个)
#!/usr/bin/perl -w
my @people = ();
$people[0]{'alternative full names for regexp'} = 'matthew smith|matt smith';
$people[1]{'alternative full names for regexp'} = 'david tennant|dave tennant';
$people[0]{'fav colour'} = 'red';
$people[1]{'fav colour'} = 'blue';
$people[0]{'fav animal'} = 'dog';
$people[1]{'fav animal'} = 'cat';
my @actors = ();
$actors[0][0] = 'David Tennant';
$actors[0][1] = 'Matt Smith';
$actors[1][0] = 'David Tennant';
$actors[1][1] = 'Matt Smith';
my @favcols = @actors;
my @favanim = @actors;
for ($i=0; $i<2; $i++) {
for ($j=0; $j<2; $j++) {
my @matching_people = grep{$actors[$i][$j] =~ m/^$_->{'alternative full names for regexp'}$/i} @people;
$favcols[$i][$j] = $matching_people[0]{'fav colour'};
$favanim[$i][$j] = $matching_people[0]{'fav animal'};
print "$matching_people[0]{'fav colour'}, $favcols[$i][$j] $matching_people[0]{'fav animal'}, $favanim[$i][$j]\n";
}
}
【问题讨论】: