Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Create an immediate core dumpInternal function used for formats (Berikutnya)
Miscellaneous functions

Catch exceptions or compile and run code

Daftar Isi

  • eval EXPR

  • eval BLOCK
  • eval

    In the first form, the return value of EXPR is parsed and executed as if itwere a little Perl program. The value of the expression (which is itselfdetermined within scalar context) is first parsed, and if there were noerrors, executed as a block within the lexical context of the current Perlprogram. This means, that in particular, any outer lexical variables arevisible to it, and any package variable settings or subroutine and formatdefinitions remain afterwards.

    Note that the value is parsed every time the eval executes.If EXPR is omitted, evaluates $_. This form is typically used todelay parsing and subsequent execution of the text of EXPR until run time.

    If the unicode_eval feature is enabled (which is the default under ause 5.16 or higher declaration), EXPR or $_ is treated as a string ofcharacters, so use utf8 declarations have no effect, and source filtersare forbidden. In the absence of the unicode_eval feature, the stringwill sometimes be treated as characters and sometimes as bytes, dependingon the internal encoding, and source filters activated within the evalexhibit the erratic, but historical, behaviour of affecting some outer filescope that is still compiling. See also the evalbytes keyword, whichalways treats its input as a byte stream and works properly with sourcefilters, and the feature pragma.

    In the second form, the code within the BLOCK is parsed only once--at thesame time the code surrounding the eval itself was parsed--and executedwithin the context of the current Perl program. This form is typicallyused to trap exceptions more efficiently than the first (see below), whilealso providing the benefit of checking the code within BLOCK at compiletime.

    The final semicolon, if any, may be omitted from the value of EXPR or withinthe BLOCK.

    In both forms, the value returned is the value of the last expressionevaluated inside the mini-program; a return statement may be also used, justas with subroutines. The expression providing the return value is evaluatedin void, scalar, or list context, depending on the context of the eval itself. See wantarray for more on how the evaluation context can be determined.

    If there is a syntax error or runtime error, or a die statement isexecuted, eval returns undef in scalar contextor an empty list in list context, and $@ is set to the errormessage. (Prior to 5.16, a bug caused undef to be returnedin list context for syntax errors, but not for runtime errors.)If there was no error, $@ is set to the empty string. Acontrol flow operator like last or goto can bypass the setting of$@. Beware that using eval neither silences Perl from printingwarnings to STDERR, nor does it stuff the text of warning messages into $@.To do either of those, you have to use the $SIG{__WARN__} facility, orturn off warnings inside the BLOCK or EXPR using no warnings 'all'.See warn, perlvar, warnings and perllexwarn.

    Note that, because eval traps otherwise-fatal errors, it is useful fordetermining whether a particular feature (such as socket or symlink)is implemented. It is also Perl's exception-trapping mechanism, wherethe die operator is used to raise exceptions.

    If you want to trap errors when loading an XS module, some problems withthe binary interface (such as Perl version skew) may be fatal even witheval unless $ENV{PERL_DL_NONLAZY} is set. See perlrun.

    If the code to be executed doesn't vary, you may use the eval-BLOCKform to trap run-time errors without incurring the penalty ofrecompiling each time. The error, if any, is still returned in $@.Examples:

    1. # make divide-by-zero nonfatal
    2. eval { $answer = $a / $b; }; warn $@ if $@;
    3. # same thing, but less efficient
    4. eval '$answer = $a / $b'; warn $@ if $@;
    5. # a compile-time error
    6. eval { $answer = }; # WRONG
    7. # a run-time error
    8. eval '$answer ='; # sets $@

    Using the eval{} form as an exception trap in libraries does have someissues. Due to the current arguably broken state of __DIE__ hooks, youmay wish not to trigger any __DIE__ hooks that user code may have installed.You can use the local $SIG{__DIE__} construct for this purpose,as this example shows:

    1. # a private exception trap for divide-by-zero
    2. eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
    3. warn $@ if $@;

    This is especially significant, given that __DIE__ hooks can calldie again, which has the effect of changing their error messages:

    1. # __DIE__ hooks may modify error messages
    2. {
    3. local $SIG{'__DIE__'} =
    4. sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
    5. eval { die "foo lives here" };
    6. print $@ if $@; # prints "bar lives here"
    7. }

    Because this promotes action at a distance, this counterintuitive behaviormay be fixed in a future release.

    With an eval, you should be especially careful to remember what'sbeing looked at when:

    1. eval $x; # CASE 1
    2. eval "$x"; # CASE 2
    3. eval '$x'; # CASE 3
    4. eval { $x }; # CASE 4
    5. eval "\$$x++"; # CASE 5
    6. $$x++; # CASE 6

    Cases 1 and 2 above behave identically: they run the code contained inthe variable $x. (Although case 2 has misleading double quotes makingthe reader wonder what else might be happening (nothing is).) Cases 3and 4 likewise behave in the same way: they run the code '$x', whichdoes nothing but return the value of $x. (Case 4 is preferred forpurely visual reasons, but it also has the advantage of compiling atcompile-time instead of at run-time.) Case 5 is a place wherenormally you would like to use double quotes, except that in thisparticular situation, you can just use symbolic references instead, asin case 6.

    Before Perl 5.14, the assignment to $@ occurred before restoration of localized variables, which means that for your code to run on olderversions, a temporary is required if you want to mask some but not allerrors:

    1. # alter $@ on nefarious repugnancy only
    2. {
    3. my $e;
    4. {
    5. local $@; # protect existing $@
    6. eval { test_repugnancy() };
    7. # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
    8. $@ =~ /nefarious/ and $e = $@;
    9. }
    10. die $e if defined $e
    11. }

    eval BLOCK does not count as a loop, so the loop control statementsnext, last, or redo cannot be used to leave or restart the block.

    An eval '' executed within the DB package doesn't see the usualsurrounding lexical scope, but rather the scope of the first non-DB pieceof code that called it. You don't normally need to worry about this unlessyou are writing a Perl debugger.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Create an immediate core dumpInternal function used for formats (Berikutnya)