10.4 A Slight Diversion: dieConsider the following a large footnote, but in the middle of the page. A filehandle that has not been successfully opened can still be used without even so much as a warning throughout the program.[ 5 ] If you read from the filehandle, you'll get end-of-file right away. If you write to the filehandle, the data is silently discarded (like last year's campaign promises).
Typically, you'll want to check the result of the open and report an error if the result is not what you expect. Sure, you can pepper your program with stuff like: unless (open (DATAPLACE,">c:/temp/dataplace")) { print "Sorry, I couldn't create c:/temp/dataplace\n"; } else { # the rest of your program }
But that sort of change is a lot of work. And it happens often enough for Perl to offer a bit of a shortcut. The
unless (open DATAPLACE,">c:/temp/dataplace") { die "Sorry, I couldn't create c:/temp/dataplace\n"; } # rest of program
But we can go even one step further. Remember that we can use the
open(DATAPLACE,">c:/temp/dataplace") || die "Sorry, I couldn't create c:/temp/dataplace\n";
So, the
The message at death (built from the argument to die "you gravy-sucking pigs"; prints the file and line number, while die "you gravy-sucking pigs\n"; does not. Another handy thing inside die strings is the $! variable, which contains the text relating to the most recent operating system error value. The variable is used like this: open(LOG, ">>logfile") || die "cannot append: $!";
The program might end up saying "
There's also the
close call
function, which most people know as open(LOG,">>log") || warn "discarding logfile output\n"; |
|