in reply to Why <c>eval {...};if ($@) { die $@ } else { ...</c> ???

Well, they could have written that as

my $res = eval { something(...); }; die $@ if $@; do_something_more(...);

But! compare

use Carp; $SIG{__DIE__} = \&Carp::confess; my $res = foo(); print "ok\n"; sub foo { local $SIG{__DIE__}; die "BANG!"; } __END__ BANG! at - line 8.

and

use Carp; $SIG{__DIE__} = \&Carp::confess; my $res = eval { foo() }; die $@ if $@; print "ok\n"; sub foo { local $SIG{__DIE__}; die "BANG!"; } __END__ BANG! at - line 9. at - line 4

I guess it's not cargo-culting... the eval BLOCK and subsequent die provides an additional frame for Carp to consider.

Replies are listed 'Best First'.
Re^2: Why eval {...};if ($@) { die $@ } else { ...???
by Jenda (Abbot) on Apr 03, 2009 at 22:55 UTC

    Well.. Actually I don't think you have to play tricks with $SIG{__DIE__} to obtain a different result. calling confess() within the something(...) would show that additional frame as well.

    I don't see any reason to want that though. What's that additional frame good for? Apart from maybe causing you to look at that part of the code and thus wasting time. I think the additional frame is at best confusing.

      What's that additional frame good for?

      something() might be in some other module which you don't control. That technique allows you to delay the exit until the very line where you choose to die. An that's precisely what eval BLOCK is all about - delay the die, to mask it or die elsewhere.

        I probably do not understand what you are trying to say. I know what's an eval BLOCK good for. I do not know what's an eval BLOCK;if ($@) {die $@}; good for.