Chapter 11. Detecting and Reporting Errors

Several things may go wrong in any program, including problems in programming, bad or missing input, unreachable external resources, and more. Perl doesn’t have any built-in error handling. It knows when it can’t do something, and it can tell me about errors, but it’s up to me as the Perl programmer to ensure that my program does the right thing and when it can’t, to try to do something useful about it.

Many of the concepts I cover in this chapter show up in various Perl modules, but I don’t want this to be a survey of Perl modules. Not only might that be out of date by the time you get this book, but as a Perl master you already know how to browse CPAN. Think about the concepts I present and evaluate those modules with what you’ve learned.

Perl Error Basics

Perl has five special variables it uses to report errors: $!, $?, $@, $^E, and ${^CHILD_ERROR_NATIVE}. Each reports different sorts of errors. Table 11-1 shows the five variables and their descriptions, which are also in perlvar:

Table 11-1. Perl’s special error reporting variables
VariableEnglishDescription
$!$ERRNO and $OS_ERRORError from an operating system or library call
$?$CHILD_ERRORStatus from the last wait() call
 ${^CHILD_ERROR_NATIVE}Error from the last child process (added in v5.10)
$@$EVAL_ERRORError from the last eval()
$^E$EXTENDED_OS_ERRORError information specific to the operating system

Operating System Errors

The simplest errors occur when Perl asks the system to do something, ...

Get Mastering Perl, 2nd 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.