Last active
August 29, 2015 14:11
-
-
Save marcoonroad/5552287e1f046b659c03 to your computer and use it in GitHub Desktop.
Exemplo de Try / Catch / Finally em Perl 5.
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 warnings; | |
sub try (&;@;) { | |
my ($try, @tests, $finally) = @_; | |
# remove o bloco <finally> se ele veio junto | |
$finally = pop (@tests) -> { 'finally' } if ref ($tests[ -1 ]) eq "HASH"; | |
push @tests, -1; # marcador de nenhum erro capturado | |
eval { &$try }; | |
if ($@) { # houve um erro? | |
local $e = $@; # erro de escopo local (como uma variável de closure) | |
for my $catch (@tests) { # propaga-o por vários blocos <catch> | |
die "Uncaught error: $e\n" if $catch == -1; # chegamos ao fim? | |
# caso contrário, segue tentando com algum outro bloco | |
last if $catch -> ( ); # poderia passar o erro <$e> como argumento | |
} | |
} # executa o bloco <finally> se ele foi definido | |
&$finally if defined $finally; | |
} | |
sub catch (&;@;) { @_ } # propagação dos blocos de baixo para cima | |
sub finally (&;) { { 'finally' => $_[ 0 ] } } # o último bloco é especial | |
try { | |
die "Bye-bye, World!"; # lança um erro | |
} # tentativas de captura | |
catch { | |
print "Caught: $e.\n" if $e =~ /hi/i; | |
} | |
catch { | |
print "Wat? -> $e ?\n" if $e =~ /hell/i; | |
} | |
# colocar um <;> no fim do último último bloco <catch> se não há um <finally> | |
# abaixo, caso contrário, o <;> precisa estar no fim do bloco <finally>... | |
catch { | |
print "See ya later...\n" if $e =~ /bye/i; | |
} | |
finally { | |
print "Surely, it works.\n"; # e o bloco que sempre é executado | |
}; # <----- olha o <;> aqui | |
try { die "---> RageQuit!" } catch { print "Caught: $e.\n" }; | |
try { 5 / 0 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment