You wrote:
> Forgive me for my dense question, but how do you return > a reference of a hash if the hash is private to the > subroutine? Can that be done?
Don't think of the hash as "private" to the subroutine; yes, it's declared lexically within the sub, but that's not all that matters. Think of the hash as a piece of data *somewhere* that you've referenced lexically within the sub.

Perl's garbage collection is based on reference counting; so each reference to such a piece of data increments the reference count. Once you've declared

my $hash = {}
the reference count of the underlying structure is incremented to one.

Normally, you'd just have that one reference to the data, so once the lexical has gone out of scope--at the end of the subroutine--the data would be destroyed. But not here, because you've returned a reference to the data and assigned it somewhere else. Even though leaving the sub decrements the reference count, then, you re-increment it by assigning the return value of the sub. So the reference count is still one, and the data is still there, and valid.

The data won't be destroyed until all references to it have gone away.

BTW: this is, as far as I know, correct, but someone who knows more about Perl's internals is free to correct anything wrong. :)


In reply to RE: (bbq) RE: Re: Another flatfile thingy by btrott
in thread Another flatfile thingy by BBQ

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.