It is horrible if you want to test for errors when writing to a file. Some errors may not show up until you close the file, due to buffering. E.g.:
open my $fh, ">/dev/full" or die "open: $!\n";
print $fh "abc\n" or die "print: $!\n";
close $fh or die "close: $!\n";
which outputs:
close: No space left on device
Dave. | [reply] [d/l] [select] |
| [reply] |
Would it be beyond the realms of possibility for that warning to be produced when a filehandle goes out of scope?
It's a default warning in 5.22.0 onwards:
$ perl5220 -e'{open my $fh, ">/dev/full"; print $fh "abc"}'
Warning: unable to close filehandle $fh properly: No space left on dev
+ice at -e line 1.
$
Dave. | [reply] [d/l] |
Letting perl close the filehandle when it goes out of scope is a common and acceptable practice. However, IMO it would be best practice to do an explicit close on write filehandles and apply error handling on it. The reason is that between the time the file was opened and when it goes out of scope a problem could have developed where the file is no longer available; such as if it was being connected to over an nfs share/mount and that mount point was lost do to some network issue. In that case, unless you were error checking all writes, you would not know about the problem until it was to late.
| [reply] |
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.
| [reply] [d/l] [select] |