eval BLOCK
If there is a syntax error or runtime error, or a die() statement is executed, an undefined value is returned by eval() , and $@ is set to the error message. If there was no error, $@ is guaranteed to be a null string. If EXPR is omitted, evaluates $_ . The final semicolon, if any, may be omitted from the expression.
Note that, since eval() traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as socket() or symlink() ) is implemented. It is also Perl's exception trapping mechanism, where the die operator is used to raise exceptions.
If the code to be executed doesn't vary, you may use the eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in $@ . Examples:
With an eval() , you should be especially careful to remember what's being looked at when:
Cases 1 and 2 above behave identically: they run the code contained in the variable $x. (Although case 2 has misleading double quotes making the reader wonder what else might be happening (nothing is).) Cases 3 and 4 likewise behave in the same way: they run the code <$x>, which does nothing at all. (Case 4 is preferred for purely visual reasons.) Case 5 is a place where normally you WOULD like to use double quotes, except that in that particular situation, you can just use symbolic references instead, as in case 6.