Created
March 19, 2013 01:45
-
-
Save yowcow/5192987 to your computer and use it in GitHub Desktop.
Minimal exception handling
This file contains hidden or 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; | |
use Carp (); | |
sub try (&@) { | |
my $try = shift; | |
my ($catch, @finally); | |
while (my ($kind, $coderef) = splice @_, 0, 2) { | |
if ($kind eq 'catch') { | |
$catch = $coderef; | |
} | |
elsif ($kind eq 'finally') { | |
push @finally, $coderef; | |
} | |
else { | |
Carp::croak '変なCB: '. ref $coderef; | |
} | |
} | |
# try | |
eval { $try->(); }; | |
# catch | |
if ($@ && defined $catch) { | |
local $_ = $@; | |
$catch->(); | |
} | |
# finally | |
$_->() for @finally; | |
} | |
sub catch (&@) { | |
catch => @_; | |
} | |
sub finally (&@) { | |
finally => @_; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment