It is also my general view, as FishMonger said, that
Letting perl close the filehandle when it goes out of scope is a common and acceptable practice.
And I have seen plenty of well written code doing just that.

I usually close my file handles explicitly, I find it easier to see in my code that I am done with such or such file. But, at least for for files in read-mode, I sometimes let the scope close the handle, especially when explicitly closing the file handle would imply binding over backward just to do that (and this can happen if your using callbacks, closures, display tables and similar constructs), whereas letting Perl do it for me is just easier.

Also, although Perl is taking care of a number of these things for you, I definitely prefer to close explicitly my files if I have further actions to do on them, especially system-related actions (reopening, copying, renaming, chmoding, sorting, sending onto another platform, etc.).

As for files in write-mode, I agree that it is certainly better to check if the OS does not report an error on closing the file. In theory at least. Because I have seen many many programs or modules that explicitly close the files but don't check the OS return value. If you don't check whether closing was successful, then explicitly closing you file handle does not buy you much (except, as I said, to show you or your maintainer that you have finished that file).

The other thing is: what actions are you going to do if close reports an error? Try again, try to recover, die? It is not always easy to figure out what to do with such exceptions. Sometimes at least, I am not sure how I should handle such exceptions.


In reply to Re: forgoing explicit file close by Laurent_R
in thread forgoing explicit file close by fionbarr

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.