next up previous contents
Next: Using the warn() Function Up: Handling Errors and Signals Previous: Using the || Logical

Using the die() Function

The die() function is used to quit your script and display a message for the user to read. Its syntax is

die(LIST);

The elements of LIST are printed to STDERR, and then the script will exit, setting the script's return value to $! (errno). If you were running the Perl script from inside a C program or UNIX script, you could then check the return value to see what went wrong.

The simplest way to use the die() function is to place it on the right side of the || operator

chdir('/user/printer') || die();

which displays

Died at test.pl line 2.

if the /user/printer directory does not exist. The message is not too informative, so you should always include a message telling the user what happened. If you don't know what the error might be, you can always display the error text associated with errno. For example:

chdir('/user/printer') || die("$!");

This line of code displays

No such file or directory at test.pl line 2.

This error message is a bit more informative. It's even better if you append the text , stopped to the error message like this:

chdir('/user/printer') || die("\$!, stopped");

which displays

No such file or directory, stopped at test.pl line 2.

Appending the extra string makes the error message look a little more professional. If you are really looking for informative error messages, try this:

$code = "chdir('/user/printer')";

eval($code) || die("PROBLEM WITH LINE: $code\n$! , stopped");

which displays the following:

PROBLEM WITH LINE: chdir('/user/printer')
No such file or directory , stopped at test.pl line 3.

The eval() function is discussed later in the section -- the eval() function executes its arguments as semi-isolated Perl code. First, the Perl code in $code is executed and then, if an error arises, the Perl code in $code is displayed as text by the die() function.

If you don't want die() to add the script name and line number to the error, add a newline to the end of the error message. For example:

chdir('/user/printer') || die("\$!\n");

displays the following

No such file or directory


next up previous contents
Next: Using the warn() Function Up: Handling Errors and Signals Previous: Using the || Logical
dave@cs.cf.ac.uk