http://qs1969.pair.com?node_id=373552


in reply to Pass by value acts like pass by reference

The question is not your hash that is changed, actually your hash is still the same, a group of pairs of keys and references to arrays. The question is the references that are in the values of your hash.

When you write

my $ref = [0 , 1 , 2 , 3] ;
you are creating an anonimous reference to an array, that is the same to write:
my @array = (0 , 1 , 2 , 3) ; my $ref = \@array ;

So, when you paste a hash as a argument to the sub, the hash is converted to an array, where we have a sequence of keys and values. The scalars that build this array (@_) will exists only inside the sub, but what you forgot is that the scalars are holding a reference to an array, and your main hash, outside the sub, is also holding this references to the same arrays. So, you are changing the same arrays and this is the meaning of references, this is why they exists.

The best way to understand is forgeting the hash and make a simple test with references:

$main_ref = [1 , 2 , 3] ; $ref2 = $main_ref ; $ref2->[0] = 'a' ; print "$main_ref->[0]\n" ; # we got 'a' $ref2 = 'not a ref anymore' ;
So, if you paste the reference you change the main array, but if you work over $ref2 and redefine it (last line) this won't change $main_ref, that still hold the reference. Now just think that the values of your hash work exaclty as this 2 scalars.

Graciliano M. P.
"Creativity is the expression of the liberty".