4.12 eval, Pattern Matching and Rule-Based Programming
Perl provides us a function called eval that can be used to evaluate or execute a Perl expression. This is a powerful function that is similar to a similarly named function in the functional programming language called Lisp. Lisp is the language of choice for many programmers in the field of Artificial Intelligence.
eval takes one argument that is either a Perl expression or a Perl block enclosed inside braces. eval executes its argument as if it were a short Perl program. This in-line program is executed in the context of the current Perl program. Therefore, any variables that were assigned before executing the argument to eval, are available inside the code argument to eval. The argument given to eval is treated like a
Perl block. So, variables declared inside this code using my or local are available only inside the block.
eval returns the value of the last expression inside the code given to it as argument. One can use the return operator to return a value from the code given to eval. If there is a syntax error or a run-time error in the code given to eval, Perl returns the undefined value undef. In such a case, an error message is put in the special variable $@. If there is
no error and the code given to eval executes correctly, $@ is set to the null string. Because of this reason, eval is regularly used as a means for evaluating an expression with the intent that if an error arises, the error is captured and handled in some manner. This is called exceptions handling, although we do not discuss it any further.