Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Pass by value acts like pass by reference

by gmpassos (Priest)
on Jul 12, 2004 at 07:19 UTC ( #373552=note: print w/replies, xml ) Need Help??

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".

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://373552]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2023-02-06 05:13 GMT
Find Nodes?
    Voting Booth?
    I prefer not to run the latest version of Perl because:

    Results (33 votes). Check out past polls.