in reply to "next" from within eval {} ?

Looks like you can't put "next" inside an "eval". You can try to refactor the code and put the checking of the return value of the "sub" outside the eval block, e.g.:

#!/usr/bin/perl -lw use strict; use diagnostics; sub do_foo { die "err" if $_==2; $_!=4 } sub do_bar { "..."; } for (1..5) { my $flag = 1; eval { $flag &&= do_foo(); $flag &&= do_bar(); }; if ($@) { warn $@; next; } next if (!$flag); print; }

Replies are listed 'Best First'.
Re^2: "next" from within eval {} ?
by dwindura (Novice) on Dec 16, 2011 at 10:28 UTC

    Just realized that my solution is different with what you want. In mine, it will still execute do_bar, eventhough do_foo returns false. The only way that I can think to break from eval is to raise an exeception, e.g.:

    #!/usr/bin/perl -lw use strict; use diagnostics; sub do_foo { die "err" if $_==2; $_!=4 } sub do_bar { "..."; } for (1..5) { eval { die 'next please' unless do_foo(); die 'next please' unless do_bar(); }; if (my $e = $@) { warn $e if ($e !~ /^next please/); next; } print; }

    Hope this is what you are looking for

      Thanks for your thoughts.

      Actually, your first suggestion was fine, and it looks like a reasonably elegant alternative to using next. Due to short-circuit evaluation, subsequent functions do in fact not execute, once the flag has become false:

      sub do_foo { print "running foo"; die "err" if $_==2; $_!=4 } sub do_bar { print "running bar"; "..."; } for (1..5) { print "-----"; my $ok = 1; eval { $ok &&= do_foo(); $ok &&= do_bar(); }; if ($@) { warn $@; next; } next unless $ok; print; } __END__ ----- running foo running bar 1 ----- running foo err at ./test.pl line 5. ----- running foo running bar 3 ----- running foo ----- running foo running bar 5

      Still, I'm not sure what's wrong with using next from within eval. I mean, you don't generate warnings without a good reason...