Skip to Content
Mastering Perl
book

Mastering Perl

by brian d foy
July 2007
Beginner content levelBeginner
342 pages
8h 30m
English
O'Reilly Media, Inc.
Content preview from Mastering Perl

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

$!

$ERRNO and $OS_ERROR

Error from an operating system or library call

$?

$CHILD_ERROR

Status from the last wait() call

$@

$EVAL_ERROR

Error from the last eval()

$^E

$EXTENDED_OS_ERROR

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Beginning Perl

Beginning Perl

Curtis Ovid Poe
Perl & LWP

Perl & LWP

Sean M. Burke
Perl by Example

Perl by Example

Ellie Quigley
Perl Hacks

Perl Hacks

Chromatic, Damian Conway, Curtis Ovid Poe, Curtis (Ovid) Poe

Publisher Resources

ISBN: 9780596527242Supplemental ContentErrata Page