I have the following example exhibiting the problem I'm struggling to resolve.
In the toy example, I have an array @actors
with two levels.
I also have an array of hashes @people
which I am using to 'look up' properties of the people in @actors
.
The output of the program should be:
blue, blue cat, cat
red, red dog, dog
blue, blue cat, cat
red, red dog, dog
but instead I'm getting:
blue, cat cat, cat
red, dog dog, dog
blue, cat cat, cat
red, dog dog, dog
That is, it seems that in setting $favanim[$i][$j]
I seem to be also overwriting the value of $favcols[$i][$j]
.
I suspect that for some reason the fact that @actors
is a 2-dimensional array means that assignments via =
are as references rather than as values, though I don't know why or how to stop it.
Please help!
The toy program is here: (I apologise if it can be simplified whilst still exhibiting the problem - it has taken me most of the afternoon to strip it down to this)
#!/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";
}
}