The last example is easily explained (except you overloaded the name 'fn' which makes your code harder to read, distracting it from the real problem).

You function returns an object, which is a reference to the lexical variable $fn. (Not, not that lexical variable $fn, the other one). $x goes out of scope when leaving fn, but $fn (right, the other one) doesn't, as there's still a reference to it. In the for loop, the reference to $fn (the other one) is aliased to $fn (right, that one). It isn't until the end of the loop that $fn (that one) is no longer an alias for a reference to $fn (not that one, the other one). At that moment, there's no reference to $fh (the other one) anymore, so the object is destroyed.

Next time, please pick some none colliding variable names.

Abigail


In reply to Re: Unpredicted late destruction by Abigail-II
in thread Unpredicted late destruction by ferrency

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.