10.5. Error Checking
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? ') {
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. ![]() |