Variables like %hash don't contain the data they represent. They point to it. So you are correct that %hash goes out of scope at the end of the sub, but the data that it points to is still there (in this example). Here's a simplified explanation as to why:

Every time something references data contained in a variable, the reference count for the data is increased by one (it should be noted that the hash and the data that it contains maintain separate reference counts, so a hash could go out of scope but some of the data still remain). When the hash is created, it is assigned a reference count of one. When you return the reference to the hash and assign it to $hash_ref, its reference count increases by one, to two. When %hash goes out of scope, the reference count is decreased by one, to one. Since it still has a reference count of one, the data is still there.

Only when $hash_ref goes out of scope (in the example above), will the reference count for the original hash drop to zero, leading Perl to remove all references to it (the data is not actually deleted, as this justs wastes time. It's merely inaccessible).

Cheers,
Ovid

Vote for paco!

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.


In reply to (Ovid - reference counts) Re: a general question on references... by Ovid
in thread a general question on references... by derek3000

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.