next up previous contents
Next: Using the die() Function Up: Handling Errors and Signals Previous: Using errno

Using the || Logical Operator

Perl provides a special logical operator that is ideal for testing the return values from functions. You may recall that the || operator will evaluate only the right operand if the left operand is false. Because most functions return false when an error occurs, you can use the || operator to control the display of error messages. For example:

chdir('/user/printer') || 
     print("Can't connect to Printer dir.\n");

This code prints only the error message if the program can't change to the /user/printer directory. Unfortunately, simply telling the user what the problem is, frequently, is not good enough. The program must also exit to avoid compounding the problems. You could use the comma operator to add a second statement to the right operand of the || operator. Adding an exit() statement to the previous line of code looks like this:

chdir('/usr/printer') || print("failure\n"), exit(1);

print("success\n");

The extra print statement is added to prove that the script really exits. If the printer directory does not exist, the second print statement is not executed.

Note

At the shell or DOS, a zero return value means that the program ended successfully. While inside a Perl script, a zero return value frequently means an error has occurred. Be careful when dealing with return values; you should always check your documentation.

Using the comma operator to execute two statements instead of one is awkward and prone to misinterpretation when other programmers look at the script. Fortunately, you can use the die() function to get the same functionality.


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