Created
February 15, 2013 05:29
-
-
Save yappo/4958713 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
sub try (&;@) { | |
my($cb, @catches) = @_; | |
local $@; | |
my $wantarray = wantarray; | |
my @ret; | |
if ($wantarray) { | |
@ret = eval { $cb->() }; | |
} elsif ( defined $wantarray ) { | |
$ret[0] = eval { $cb->() }; | |
} else { | |
eval { $cb->() }; | |
}; | |
my $e = $@; | |
return @ret unless defined $e; | |
for (my $i = 0;$i < @catches;$i += 2) { | |
if (UNIVERSAL::isa($e, $catches[$i])) { | |
local $_ = $e; | |
$catches[$i + 1]->(); | |
return; | |
} | |
} | |
die $e; | |
} | |
package MyEx { | |
use parent 'Exception::Tiny'; | |
} | |
package YourEx { | |
use parent 'Exception::Tiny'; | |
} | |
try { | |
MyEx->throw; | |
} | |
'MyEx' => sub { warn }, | |
'YourEx' => sub { warn }; | |
try { | |
YourEx->throw; | |
} | |
'MyEx' => sub { warn }, | |
'YourEx' => sub { warn }; | |
try { | |
die 'gerry'; | |
} | |
'MyEx' => sub { warn }, | |
'YourEx' => sub { warn }; | |
__END__ | |
MyEx at ./Try.pl line 39. at ./Try.pl line 41. | |
YourEx at ./Try.pl line 45. at ./Try.pl line 48. | |
gerry at ./Try.pl line 51. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment