Chapter 12. Detecting and Reporting Errors
Several things may go wrong in any program, including problems in programming, bad or missing input, unreachable external resources, and many other things. Perl doesn’t have any built-in error handling. It knows when it couldn’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, try to do something useful about it.
Perl Error Basics
Perl has four special variables it uses to report errors: $!, $?, $@, and
$^E. Each reports different sorts of
errors. Table 12-1 shows the four variables and
their descriptions, which are also in perlvar.
Table 12-1. Perl’s special error-reporting variables
Variable | English | Description |
|---|---|---|
|
| Error from an operating system or library call |
|
| Status from the last |
|
| Error from the last
|
|
| Error information specific to the operating system |
Operating System Errors
The simplest errors occur when Perl asks the system to do
something, but the system can’t or doesn’t do it for some reason. In
most cases the Perl built-in returns false and sets $! with the error message. If I try to read a
file that isn’t there, open returns
false and puts the reason it failed in $!:
open my( $fh ), '<', 'does_not_exist.txt'
or die "Couldn't open file! $!";
The Perl interpreter is a C program, and it does its work through the library of C functions it’s built upon. The value ...