There are some subtleties associated with the way quotes or blocks are interpreted by Perl. Consider the differences between the following statements:
$str = '$c = 10'; # eval $str; # 1 eval "$str"; # 2 eval '$str'; # 3 eval { $str }; # 4
Cases 1 and 2 have identical results, and cases 3 and 4 behave identically. Can you see why? The trick is to know what the interpreter does before handing it over to eval.
In case 1, Perl gives the contents of $str to eval, just as it would for any other function. Hence eval sees the string '$c
= 10'
, treats it like a little program, and executes it.
In case 2, Perl does variable interpolation on the double-quoted string before handing it over to eval. Again, eval sees the contents of $str, compiles it, and executes it, assigning 10 to $c.
In case 3, the argument to eval is a single-quoted string, which is not expanded during the variable interpolation stage. For this reason, eval sees a hardcoded string (with the characters "$", "s", "t", "r") and treats it like a little program as before. As a standalone program, it is quite useless, of course. Since eval returns the result of the last expression, it returns the value of $str (the string $c = 10). That is, if you say,
$s = eval '$str';
$s will contain $c = 10.
Case 4 is identical to case 3, except that the code inside the block is checked for syntax errors at compile-time (at the same time as the rest of the script).
That's all there is to know about eval. Now, let us see how to use it for expression evaluation, exception handling, and efficiency.