Skip to content

Commit

Permalink
Restore list context for catch and fix a bug in finally with no catch
Browse files Browse the repository at this point in the history
  • Loading branch information
nothingmuch committed Jan 22, 2010
1 parent ba82008 commit 82ef0e6
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 14 deletions.
19 changes: 9 additions & 10 deletions lib/Try/Tiny.pm
Expand Up @@ -84,6 +84,9 @@ sub try (&;@) {
$error = $@;
}

# set up a scope guard to invoke the finally block at the end
my $guard = $finally && bless \$finally, "Try::Tiny::ScopeGuard";

# at this point $failed contains a true value if the eval died, even if some
# destructor overwrote $@ as the eval was unwinding.
if ( $failed ) {
Expand All @@ -92,13 +95,7 @@ sub try (&;@) {
# This works like given($error), but is backwards compatible and
# sets $_ in the dynamic scope for the body of C<$catch>
for ($error) {
my $catch_return = $catch->($error);

# Finally blocks run after all other blocks so it is executed here
$finally->() if ( $finally );

#And return whatever catch returned
return $catch_return;
return $catch->($error);
}

# in case when() was used without an explicit return, the C<for>
Expand All @@ -107,9 +104,6 @@ sub try (&;@) {

return;
} else {
# Execute finally block once we decided we worked
$finally->() if ( $finally );

# no failure, $@ is back to what it was, everything is fine
return $wantarray ? @ret : $ret[0];
}
Expand All @@ -133,6 +127,11 @@ sub finally (&;@) {
);
}

sub Try::Tiny::ScopeGuard::DESTROY {
my $self = shift;
$$self->();
}

__PACKAGE__

__END__
Expand Down
10 changes: 7 additions & 3 deletions t/basic.t
Expand Up @@ -3,7 +3,7 @@
use strict;
#use warnings;

use Test::More tests => 24;
use Test::More tests => 26;

BEGIN { use_ok 'Try::Tiny' };

Expand Down Expand Up @@ -72,8 +72,12 @@ throws_ok {
is( $@, "magic", '$@ untouched' );
}

is( scalar(try { "foo", "bar", "gorch" }), "gorch", "scalar context" );
is_deeply( [ try {qw(foo bar gorch)} ], [qw(foo bar gorch)], "list context" );
is( scalar(try { "foo", "bar", "gorch" }), "gorch", "scalar context try" );
is_deeply( [ try {qw(foo bar gorch)} ], [qw(foo bar gorch)], "list context try" );

is( scalar(try { die } catch { "foo", "bar", "gorch" }), "gorch", "scalar context catch" );
is_deeply( [ try { die } catch {qw(foo bar gorch)} ], [qw(foo bar gorch)], "list context catch" );


{
my ($sub) = catch { my $a = $_; };
Expand Down
2 changes: 1 addition & 1 deletion t/finally.t
Expand Up @@ -3,7 +3,7 @@
use strict;
#use warnings;

use Test::More tests => 7;
use Test::More tests => 8;

BEGIN { use_ok 'Try::Tiny' };

Expand Down

0 comments on commit 82ef0e6

Please sign in to comment.