In praise of Try::Tiny
Try::Tiny is one of those tools that feels like it should always be in your toolbox. Handling exceptions in Perl is awkward; Java, JavaScript, Python, and Objective-C all provide native try syntax. Perl does, mostly, via eval {} blocks, but it's hinky. Errors coming out of the block aren't local by default, and it's almost a dozen lines of boilerplate to add it properly.
Enter Try::Tiny:
use Try::Tiny;
my $foo;
my $output;
try {
$output = $foo->plover() || DEFAULT_PLOVER;
} catch {
if ( /^Can't call method/ ) {
die "No magic!\n";
} else {
# Proceed
}
};
It's just clean and easy-peasy. Things feel natural, there are no dependencies, and it obviates the many subtle things you can do wrong with evaluation in Perl. Try::Tiny is the the new hotness. (I got it added to the base library at work and am slowly converting a bunch of eval {} blocks with potential action-at-a-distance issues.)
(Addendum: Yuval Kogman wrote me to not that this can be better written:
my $output = try { $foo->plover... };
That's a perfectly readable way to do it!)
Try::Tiny is one of those small, fantastic modules which just hits the sweet spot.