10.3. A Slight Diversion: die

Consider this a large footnote, 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[1] throughout the program. 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).

[1] Unless you are running with the -w switch enabled.

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,">/tmp/dataplace")) {
    print "Sorry, I couldn't create /tmp/dataplace\n";
} else {
    # the rest of your program
}

But that's a lot of work. And it happens often enough for Perl to offer a bit of a shortcut. The die function takes a list within optional parentheses, spits out that list (like print) on the standard error output, and then ends the Perl process (the one running the Perl program) with a nonzero exit status (generally indicating that something unusual happened[2]). So, rewriting the chunk of code above turns out to look like this:

unless (open DATAPLACE,">/tmp/dataplace") {
    die "Sorry, I couldn't create /tmp/dataplace\n";
}
# rest of program

[2] Actually, die merely raises an exception, but since you aren't being shown how to trap exceptions, it behaves as described. See eval in Chapter 3 of Programming Perl or perlfunc (1) for details.

But we can go even ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.