Fatal Errors with die
Let’s step aside for a moment. We need some stuff that isn’t directly related to (or limited to) I/O, but is more about getting out of a program earlier than normal.
When a fatal error happens inside Perl (for example, if you divide
by zero, use an invalid regular expression, or call a subroutine that
hasn’t been declared), your program stops with an error message telling
why.[‖] But this functionality is available to us with the die function, so we can make our own fatal
errors.
The die function prints out the
message you give it (to the standard error stream, where such messages
should go) and makes sure that your program exits with a nonzero exit
status.
You may not have known it, but every program that runs on Unix (and many other modern operating systems) has an exit status, telling whether it was successful or not. Programs that run other programs (like the make utility program) look at that exit status to see that everything happened correctly. The exit status is just a single byte, so it can’t say much; traditionally, it is 0 for success and a nonzero value for failure. Perhaps 1 means a syntax error in the command arguments, while 2 means that something went wrong during processing, and 3 means the configuration file couldn’t be found; the details differ from one command to the next. But 0 always means that everything worked. When the exit status shows failure, a program like make knows not to go on to the next step.
So we could rewrite the previous example, ...