Документация
HTML CSS PHP PERL другое

Section 2.3.  Dynamic Code with eval

 
Previous
Table of Contents
Next

2.3. Dynamic Code with eval

There's also a second form of eval, whose parameter is a string expression instead of a block. It compiles and executes code from a string at runtime. While this is useful and supported, it is also dangerous if any untrustworthy data has gotten into the string. With a few notable exceptions, we recommend you avoid eval on a string. We'll use it a bit later, and you might see it in other people's code, so we'll show you how it works anyway.

eval '$sum = 2 + 2';
print "The sum is $sum\n";

Perl executes that code in the lexical context of the code around it, meaning that it's virtually as if we had typed that code right there. The result of the eval is the last evaluated expression, so we really don't need the entire statement inside the eval.

#!/usr/bin/perl

foreach my $operator ( qw(+ - * /) ) {
        my $result = eval "2 $operator 2";
        print "2 $operator 2 is $result\n";
        }

Here, we go through the operators + - * / and use each of those inside our eval code. In the string we give to eval, we interpolate the value of $operator into the string. The eval executes the code that the string represents and returns the last evaluated expression, which we assign it to $result.

If eval can't properly compile and run the Perl code we hand it, it sets $@ just like in its block form. In this example, we want to trap any divide-by-zero errors, but we don't divide by anything (another sort of error).

print 'The quotient is ', eval '5 /', "\n";
warn $@ if $@;

The eval catches the syntax error and puts the message in $@, which we check immediately after calling eval.

The quotient is
syntax error at (eval 1) line 2, at EOF

Later, in Chapters 10, 17, and 18, we'll use this to optionally load modules. If we can't load the module, Perl normally would stop the program. We'll catch the error and recover on our own when this happens.

In case you didn't catch our warning before, we'll say it again: be very careful with this form of eval. If you can find another way to do what you need, try that first. We'll use it later, in Chapter 10 to load code from an external file, but then we'll also show you a much better way to do that too.


Previous
Table of Contents
Next
© 2000- NIV