Will code after eval(die "some error message") continue to be executed?

die, eval, perl

Solution

You're evaling result of

opendir(BASEDIR,$baseDir) or die "dir doesn't exist!\n"

code. If it would succeed that would be equivalent of `eval(1)`.

What you want is `eval BLOCK`:

my $eval_rtn = eval{ opendir(BASEDIR,$baseDir) or die "dir doesn't exist!\n" };

Check perldoc -f eval for difference between `eval EXPR` and `eval BLOCK`

Problem

I know that in java language ,if an exception is catched successfully ,the code after the try-catch-clause will still run.In perl ,it uses eval to catch exception.So ,I write two simple programs to test it. testEval1.pl: ``` $exp = '$i = 3; die "error message"; $k = $i + $j'; push ( @program, '$i = 3; die "error message"; $k = $i + $j'); $rtn =eval($exp); if ( ! defined ( $rtn)) { print "Exception: " , $@,"\n"; } else { print $rtn,"\n"; } ``` output of testEval1.pl: ``` code continue to run after die! Exception: error message at (eval 1) line 1. ``` testEval2.pl ``` $baseDir = "/home/wuchang/newStore1"; my $eval_rtn = eval(opendir(BASEDIR,$baseDir) or die "dir doesn't exist!\n"); print "code continue to run after die!\n"; if(!defined($eval_rtn)){ print $@; } else { print $rtn,"\n"; } ``` output of testEval2.pl: ``` dir doesn't exist! ``` you can see that in the two code examples , the code block of eval both has die expressions.But in testEval1.pl,the code after eval can be excuted,while in testEval2.pl,it's not! So ,my question is ,what's the difference ? What can I do to make the program continue to run even if a "dir doesn't exist" exception happeded ? thank you.

Original source