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


In reply to Re: Pass by value acts like pass by reference by gmpassos
in thread Pass by value acts like pass by reference by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.