Name

eval

Synopsis

eval string eval {block}

Description

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

Get Perl in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.