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 theeval
last only until theeval
is done. (See alsolocal
andmy
.) The value returned from aneval
is the value of the last expression evaluated. Like subroutines, you may also use thereturn
function to return a value and exit theeval
.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 ofeval
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, theeval
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 adie
statement is encountered), theeval
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.