Simplifying a bit, references point to a memory location of a data structure. In your first piece of code, my $result_hr; will be undef because it isn't initialized. In your sub, you copy the elements of @_ into $raw_hr and $res_hr, so now $res_hr is just a copy of the original undef. In other words, it doesn't point anywhere! And $res_hr has no way to affect $result_hr. There is a hash being autovivified, but it is restricted to the scope of the sub.

When you write my $result_hr={};, now what is being passed into the sub is a reference that points to an anonymous hash. The reference still gets copied into $res_hr, but the result of that is just two references pointing at the same data structure. The hash isn't being autovivified in sub, instead the sub is modifying the anonymous hash pointed to by both $result_hr and $res_hr. When the sub returns, your main code still has access to the anonymous hash via the reference stored in $result_hr.

Note that there is a way to modify $result_hr from within the sub: use $_[1] directly, instead of $res_hr, because the elements of @_ are aliases to the original arguments. However, I wouldn't normally recommend this way of modifying arguments, because that they are in effect return values can be confusing to users of the API. It's more common to handle this via regular return values.

(Update before posting: I see davido has explained the same thing, with different wording - TIMTOWTDI :-) )


In reply to Re: passing a hash ref in a sub by haukex
in thread passing a hash ref in a sub by frazap

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.