There's been a good bit of decent discussion on this, and I'm guessing you've gotten most of your questions answered. One thing I didn't really see mentioned is a bit on the "why" of it.

When you create a new IO::File object, you are, obviously, creating an object for your filehandle and assigning it to a variable. After you finish with it, you can call $fh_var->close; to explicitly close your file. Personally, I'm a big fan of this, as it makes your intentions clear and it's a good habit to clean up after yourself.

If you undef the variable, you get the same behavior as the variable going out of scope, which is that Perl will automatically clean up (the equivalent of a DESTROY() method) after you and close the file; as the object no longer has any references to it, there is no way to access the file, so it is "garbage collected", so to speak.

Neither the the explicit close function nor the variable undef is really better or worse than the other, although they do offer different trade-offs. For example, if you do an explicit close, you can re-use for IO::File object to open a new file. If you undefine the object reference, you will need a new object if you wanted to open a new file.

Christopher Cashell

In reply to Re: A Few Questions About IO::File by topher
in thread A Few Questions About IO::File by rpetrelli

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.