ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
3.2.32 evaleval The value expressed by The value returned from an eval is the value of the last expression evaluated, just as with subroutines. Similarly, you may use the return operator to return a value from the middle of the eval. If there is a syntax error or run-time error (including any produced by the die operator), eval returns the undefined value and puts the error message in $@. If there is no error, $@ is guaranteed to be set to the null string, so you can test it reliably afterward for errors. Here's a statement that assigns an element to a hash chosen at run-time: eval "\$$arrayname{\$key} = 1"; (You can accomplish that more simply with soft references - see "Symbolic References" in Chapter 4, References and Nested Data Structures.) And here is a simple Perl shell: while (<>) { eval; print $@; } Since eval traps otherwise-fatal errors, it is useful
for determining whether a particular feature (such as socket or
symlink) is implemented.
In fact, eval is the way to do all
exception handling in Perl. If the code to be executed doesn't vary,
you should use the
# make divide-by-zero non-fatal eval { $answer = $a / $b; }; warn $@ if $@; # same thing, but less efficient eval '$answer = $a / $b'; warn $@ if $@; # a compile-time error (not trapped) eval { $answer = }; # a run-time error eval '$answer ='; # sets $@ Here, the code in the With an eval you should be careful to remember what's being looked at when: eval $x; # CASE 1 eval "$x"; # CASE 2 eval '$x'; # CASE 3 eval { $x }; # CASE 4 eval "\$$x++"; # CASE 5 $$x++; # CASE 6 Cases 1 and 2 above behave identically: they run the code contained in
the variable A frequently asked question is how to set up an exit routine.
One common way is to use an #!/usr/bin/perl eval <<'EndOfEval'; $start = __LINE__; . . # your ad here . EndOfEval # Cleanup unlink "/tmp/myfile$$"; $@ && ($@ =~ s/\(eval \d+\) at line (\d+)/$0 . " line " . ($1+$start)/e, die $@); exit 0; Note that the code supplied for an eval might not
be recompiled if the text hasn't changed. On the rare occasions when you want
to force a recompilation (because you want to reset a eval $prog . '#' . ++$seq; |