22 February 2009
This post may be outdated due to it was written on 2009. The links may be broken. The code may be not working anymore. Leave comments if needed.
Updated: Thanks for Eddy to point out the errors. :)

I have been very happy with Scope::Guard recently.

mainly the module can reduce the size of the code if you use it correctly.

for example, we have some piece of code like follows to deal with Sphinx error.
sub while_error {
my ( $ret ) = @_;

my $use_db = { use_db_please => 1 };

# 1, connection to {localhost}:{3312} failed: Connection refused
if ($ret->{error} =~ /Connection refused/is) {
faked_try_to_reconnect();
print STDERR "$ret->{error}\n";
return $use_db;
}
# 2, received zero-sized searchd response
elsif ($ret->{error} =~ /zero-sized searchd/) {
faked_try_to_re_search();
print STDERR "$ret->{error}\n";
return $use_db;
}
# 3, unknown local index
elsif ( $ret->{error} =~ /unknown local index/ ) {
faked_try_to_re_index();
print STDERR "$ret->{error}\n";
return $use_db;
}
# 4, recv: Connection reset by peer
elsif ( $ret->{error} =~ /Connection reset by peer/ ) {
print STDERR "$ret->{error}\n";
return $use_db;
}
return $ret;
}
OK, it's not so ugly.
but with Scope::Guard, we can rewrite it much more clear and small-size.
sub while_error {
my ( $ret ) = @_;

my $use_db = { use_db_please => 1 };

my $sg = Scope::Guard->new( sub {
print STDERR "$ret->{error}\n";
} );

# 1, connection to {localhost}:{3312} failed: Connection refused
if ($ret->{error} =~ /Connection refused/is) {
faked_try_to_reconnect();
return $use_db;
}
# 2, received zero-sized searchd response
elsif ($ret->{error} =~ /zero-sized searchd/) {
faked_try_to_re_search();
return $use_db;
}
# 3, unknown local index
elsif ( $ret->{error} =~ /unknown local index/ ) {
faked_try_to_re_index();
return $use_db;
}
# 4, recv: Connection reset by peer
elsif ( $ret->{error} =~ /Connection reset by peer/ ) {
return $use_db;
}

$sg->dismiss();

return $ret;
}
I'm not sure if you're happy with it or not, but I like it. :)
I had used it in http://code.fayland.org/fayland/CPAN/day_day_up/lib/DayDayUp/Backup.pm. that's just another example.

Thanks and Enjoy!


blog comments powered by Disqus