The 'eval EXPR' version evaluates code at runtime like you expect while the 'eval BLOCK' version is used for exception handling (and is not evaluated at runtime).

For example normally DBI errors are fatal to the entire program. However, if I wrap my DBI calls in an eval BLOCK structure I can then catch a fatal DBI error and take steps to deal with that in my program such as logging it, restarting the database connection, etc. The important thing is that the fatal error doesn't take my script with it.

Personally I think using the same name is confusing. I would have preferred something like 'catch BLOCK' instead (or perhaps 'exception BLOCK').

Here's some 'eval BLOCK' code I use:

sub cmd_wrapper { my( $cmd ) = @_; my( $rc , $out ); eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 15; $out = (`$cmd`)[0]; # Get first line of output $rc = $?; alarm 0; }; if( $@ ) { die "Eval failed for $cmd but not because of alarm" if $@ ne " +alarm\n"; # Propogate unexpected errors die "Eval failed for $cmd because alarm timed out"; } die "Return code undefined for $cmd" unless defined $rc; return $rc, $out if wantarray; return $rc; }

See also Corion's post: Re: nested variable resolution.


In reply to Re^3: nested variable resolution by Argel
in thread nested variable resolution by mpettis

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.