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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|