Perl in a Nutshell

Perl in a NutshellSearch this book
Previous: Reference: eofChapter 5
Function Reference
Next: Reference: exec
 

eval

eval string
eval {block}

Evaluates the expression or code in its argument at runtime as a separate Perl program within the context of the larger script. Any variable settings remain afterward, as do any subroutine or format definitions. The code of the eval is treated as a block, so any locally scoped variables declared within the eval last only until the eval is done. (See also local and my.) The value returned from an eval is the value of the last expression evaluated. Like subroutines, you may also use the return function to return a value and exit the eval.

With eval string, the contents of string are compiled and executed at runtime. For example:

$a = 3, $b = 4;
$c = '$a * $b';
print (eval "$c"); # prints 12
The string form of eval is useful for executing strings produced at runtime from standard or other dynamic input sources. If the string produces an error, either from syntax or at runtime, the eval exits with the undefined value and places the error in $@. If string is omitted, the operator evaluates $_.

The block form of eval is used in Perl programs to handle runtime errors (exceptions). The code in block is compiled only once during the compilation of the main program. If there is a syntax error in the block it will produce an error at compile time. If the code in block produces a runtime error (or if a die statement is encountered), the eval exits, and the error is placed in $@. For example, the following code can be used to trap a divide-by-zero error at runtime:

eval {
      $a = 10; $b = 0;
      $c = $a / $b;     # causes runtime error
                        # trapped by eval
     };
print $@;               # Prints  "Illegal division by 0 at try.pl line 3"
As with any code in a block, a final semicolon is not required.


Previous: Reference: eofPerl in a NutshellNext: Reference: exec
Reference: eofBook IndexReference: exec