perl - Why does my value change when I am not resetting it? -


i have following example exhibiting problem i'm struggling resolve. in toy example, have array @actors 2 levels. have array of hashes @people using 'look up' properties of people in @actors.

the output of 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, seems in setting $favanim[$i][$j] seem overwriting value of $favcols[$i][$j]. suspect reason fact @actors 2-dimensional array means assignments via = references rather values, though don't know why or how stop it. please help!

the toy program here: (i apologise if can simplified whilst still exhibiting problem - has taken me of afternoon strip down this)

#!/usr/bin/perl -w  @people = (); $people[0]{'alternative full names regexp'} = 'matthew smith|matt smith'; $people[1]{'alternative full names 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';  @actors = (); $actors[0][0] = 'david tennant'; $actors[0][1] = 'matt smith'; $actors[1][0] = 'david tennant'; $actors[1][1] = 'matt smith'; @favcols = @actors; @favanim = @actors;  ($i=0; $i<2; $i++) {   ($j=0; $j<2; $j++) {     @matching_people = grep{$actors[$i][$j] =~ m/^$_->{'alternative full names 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";   } } 

try using

@favcols = map { [@$_] } @actors; @favanim = map { [@$_] } @actors; 

deep copy vs shallow copy.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -