Using Eval for Expression Evaluation
There are a number of tasks, such as parsing and expression evaluation, in which you can make Perl do all the dirty work. Assuming, of course, that your parsing requirements are similar to Perl’s own. Perl, after all, knows a thing or two about parsing and evaluating Perlish statements!
Let’s assume that your input data is a bunch of quoted strings and you would like to verify that the quotes are balanced:
'He said, "come on over"' 'There are times when "Peter" doesn\'t work at all'
Instead of fretting over backslash escapes and writing code to check
whether the quotes are correctly paired (balanced), you can simply
eval
the strings, as shown in Example 5.1. Remember that a string is a correct Perl
expression too. If Perl puts an error in $@
, you
can be sure you have faulty input.
Example 5-1. eval.pl
while (defined($s = <>)) { # Read a line into $s $result = eval $s; # Evaluate that line if ($@) { # Check for compile or run-time errors. print "Invalid string:\n $s"; } else { print $result, "\n"; } }
The neat thing about this code is that
it works equally well as a fancy calculator, because
$s
can be any valid Perl
statement, with arithmetic operators, loops, variable assignments,
subroutines, and so on. Here’s how you might use the program:
% perl eval.pl 2 * log (10); 4.60517018598809 $a = 10; $a += $a ** 2; 110 for (1..10) {print $_ , " " } 1 2 3 4 5 6 7 8 9 10
For each line you enter, Perl computes and prints out the result (shown in non-bold ...
Get Advanced Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.