Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (6)
As of 2024-04-19 16:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found