eval
in all its forms is used to execute a little Perl program, trapping any errors encountered so they don't crash the calling program.
Plain eval
with no argument is just eval EXPR
, where the expression is understood to be contained in $_
. Thus there are only two real eval
forms; the one with an EXPR is often called "string eval". In a string eval, the value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This form is typically used to delay parsing and subsequent execution of the text of EXPR until run time. Note that the value is parsed every time the eval
executes.
The other form is called "block eval". It is less general than string eval, but the code within the BLOCK is parsed only once (at the same time the code surrounding the eval
itself was parsed) and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first, while also providing the benefit of checking the code within BLOCK at compile time. BLOCK is parsed and compiled just once. Since errors are trapped, it often is used to check if a given feature is available.
In both forms, the value returned is the value of the last expression evaluated inside the mini-program; a return statement may also be used, just as with subroutines. The expression providing the return value is evaluated in void, scalar, or list context, depending on the context of the eval
itself. See wantarray
for more on how the evaluation context can be determined.
If there is a syntax error or runtime error, or a die
statement is executed, eval
returns undef
in scalar context, or an empty list in list context, and $@
is set to the error message. (Prior to 5.16, a bug caused undef
to be returned in list context for syntax errors, but not for runtime errors.) If there was no error, $@
is set to the empty string. A control flow operator like last
or goto
can bypass the setting of $@
. Beware that using eval
neither silences Perl from printing warnings to STDERR, nor does it stuff the text of warning messages into $@
. To do either of those, you have to use the $SIG{__WARN__}
facility, or turn off warnings inside the BLOCK or EXPR using no warnings 'all'
. See warn
, perlvar, and warnings.
Note that, because eval
traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as socket
or