10.5. Error Checking
Never open, close, or print to a file without checking the outcome .
These three I/O functions are probably the ones that fail most often. They can fail because a path is bad, or a file is missing, or inaccessible, or has the wrong permissions, or a disk crashes, or the network fails, or the process runs out of file descriptors or memory, or the filesystem is read-only, or any of a dozen other problems.So writing unguarded I/O statements like this:
open my $out, '>', $out_file;
print {$out} @results;
close $out;
is sheer optimism, especially when it's not significantly harder to check that everything went to plan:
open my $out, '>', $out_file or croak "Couldn't open '$out_file': $OS_ERROR";
print {$out} @results or croak "Couldn't write '$out_file': $OS_ERROR";
close $out or croak "Couldn't close '$out_file': $OS_ERROR";
Or, more forgivingly, as part of a larger interactive process:
SAVE:
while (my $save_file = prompt 'Save to which file? ') {
# Open specified file and save results...
open my $out, '>', $save_file or next SAVE;
print {$out} @results or next SAVE;
close $out or next SAVE;
# Save succeeded, so we're done...
last SAVE;
}
Also see the "Builtin Failures" guideline in Chapter 13 for a less intrusive way to ensure that every open, print, and close is properly checked.Checking every print to a terminal device is also laudable, but not essential. Failure in such cases is much rarer, and usually self-evident. Besides, if your print statements can't reach the terminal, it's unlikely that your warnings or exceptions will either.