Perl's die, warn, and eval Functions

Source: Internet
Author: User
Tags chop win32 error win32 error codes perl script

Die Function

18.4 handle errors

In many cases, system calls may fail. For example, you can try to open a non-existing file, delete a directory that still contains the file, or

Try to read files without read permission. In the previous example, we have used the die function. This section details error handling and error

Error handling function content. These functions include the die function, warn function, and eval function.

The die function is used to exit the Perl script when the command or file handle fails.

The warn function is similar to the die function, but it does not exit the script.

The eval function has multiple functions, but it is mainly used for exception handling.

The reader must remember the short-circuit operator & |. These two operators first obtain the value of the left operand before obtaining the value of the right operand.

. If the value of the & left operation is true, the right operand is required. If | the value of the left operand is false, the operation on the right is required.


Carp. PM module. There are many ways to exit the script for users to choose from. The carp module provided by Perl 5 extends the functions of die and warn. (Details

See example 12.10 .)

18.4.1 die Function

If the system call fails, the die function prints the string to stderr and uses $! To exit the script. $! The variable contains errno.

The current value, which is a UNIX global variable and contains a number indicating a system error. Errno is updated only when the system call fails.

. When the system call fails, a digital code is assigned to errno to indicate the error type. If the linefeed is omitted in the string,

The message with a row number is printed (see the complete list in/usr/include/sys ).

The following is an example in the/usr/include/sys/errno. h file:

# Define eperm 1/* not owner */# define enoent 2/* no such file or directory */# define esrch 3 /*

No such process */# define eintr 4/* interrupted system call */# define EIO 5/* I/O Error */

Win32 error codes are different from UNIX error codes, so they cannot depend on $! Returned value. Many Win32 extensions provide their own error messages.

To provide more meaningful results. For more information, see Win32: getlasterror in the standard Perl library in ActiveState.



Die (list) Die listdie

Example 18.66

(In script) 1 die "can't CD to junk: $! \ N "Unless chdir"/usr/bin/junk "; (output) 1 can't CD

Junk: no such file or directory


1. chdir call failed. $! Contains error messages from errno. Line Break causes the string following the die function to be printed, which contains

Variable $! .

Example 18.67

(In script) 1 die unless chdir '/plop'; (output) 1 died at croak. Perl line 4.


1. chdir call failed. This time $! Print the row with an error not in the die string.

Example 18.68

(In script) 1 chdir '/plop' or die "STOPPED"; (output) 1 stopped at croak. Perl line 4.


1. The output content in this example is the same as that in the previous example, but it uses different syntaxes. If the chdir call fails, run the die letter on the or side.


Warn Function

The warn function (operator) is almost the same as the die function. The difference is that the former will allow the program to continue running. If the die function is called in the eval block

The parameter string passed to die is also assigned to the Special variable $ @. After calling die, the variable can be passed as a parameter to the warn function,

The output will be sent to stderr (see the ecal function section ).

Eval function

The eval function is used to handle exceptions, that is, catch errors. The statement block after Eval is processed and parsed as a separate perl program.

Some variable settings, subroutines, and format definitions are maintained until the eval execution is complete.

The value returned by the eval function is the value of the previous expression. If a compilation or running error occurs or the die statement is executed

Defines the value and sets the special variable $ @ as the error message content. If no error occurs, $ @ is a null string.

Evaluate the Perl expression value with Eval

Example 18.69

(The script)

#! /Bin/perl

# The eval function will evaluate each line you type

# And return the result. It's as though you are

# Running a little independent Perl script.

# Script Name: plsh1

Print ">"; # print the prompt2 while (<stdin>) {3 $ result = eval;

# Eval evaluates the expression $ _ 4 warn $ @ if $ @;

# If an error occurs, it will be assigned toprint "$ Result \ n if $ result"; 6 print "> ";

# Print the prompt} (output) (the command line) $ plsh2> hello5 hello2> bye5 bye2> 5

+ 45 92> 8/35 2.666666666666672> 5/04 illegal division by zero at (eval 5) line 3, <stdin>

Line 5.> "Oh I seecan't find string Terminator '" 'anywhere before EOF at (eval 6) Line 1, <stdin>

Line> exit


1. The bank prints a prompt to the user. This program is similar to a small Perl shell. It can help users check the expressions before putting them into the program

Check whether the expression is good or bad, especially when you are not sure how Perl will process the expression.

2. Enter the while loop. Every time you enter the loop, read a row of input from the user and assign it to $ _.

3. Eval without parameters evaluates the expression $ _ and assigns the result $ result.

4. If eval finds a syntax error or system error caused by the evaluate expression, it will assign the returned error message to the variable $ @. If no

If an error is found, $ @ is assigned a null string.

5. If the expression is successfully evaluated, print the result.

6. display the prompt information and enter the loop again.

Use eval to catch errors in the program

Example 18.70

(In script )#! /Bin/perlprint "give me a number."; chop ($ A = <stdin>); print "give me a divisor."; chop

($ B = <stdin>); 1 eval {die unless $ answer = $ A/$ B;}; 2 warn $ @ ifprintf "division of %. 2f by %. 2f

Is %. 2f. \ n ", $ A, $ B, $ answer if $ answer; 4 print" I'm here now. Good-day! \ N "; (output) Give me

Number.45give me a divisor.63 division of 45.00 by 6.00 is 7.50.4 I'm here now. Good-day!

(Output) Give me a number.5give me a divisor.02 illegal division by zero at./eval. P line 8,

<Stdin> line 2.4 I'm here now. Good-day!


1. the eval function calculates the Division ($ A/$ B) and saves the result to $ answer. Note that you must first use $ answer in eval.

Keep until the eval execution ends.

2. If everything is normal and Division operations are completed successfully, ignore this line. If an error is found (for example, dividing by 0), set the $ @ variable

System error information, print the message to stderr through the warn function, and resume program execution. If the die function is called in the eval block

The program does not exit, but continues execution after exiting the eval block.

3. If the operation is successful, the result of the division operation is printed.

4. Print the row to explain that the program will continue to run even if it fails, because the warn function will not cause the script to exit.

Eval functions and here documents

Example 18.71

(The script )#! /Bin/perl1 eval <"EOF"; 2 chdir "Joker" | die "can't CD: $! \ N "; 3 eof4 print"

Error message from die: Print "program $0 still in progress. \ n"; (output) 4 the error message from

Die: Can't CD: no such file or directory5 program./eval4.p still in progress.


1. The here document is similar to a special form of reference. The eval function obtains all content between the first EOF and the last EOF.

2. If the chdir function fails to be called, call the die function and restore the program after the last eof in the here document.

3. eof indicates that the here document ends here.

4. Save the error message of the die function in the variable $.

5. The program continues to be executed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.