While perl does not have a formal mechanism for
finally blocks, you can indeed easily emulate them with an object that has a destructor.
(
update: MeowChow beat me by pointing out
an easier/already-in-CPAN way to do this.)
#>>> DummyDestructor.pm
package DummyDestructor;
use strict;
use vars qw(@ISA @EXPORT);
require Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(make_finally);
sub make_finally (\&) {
return bless $_[0], __PACKAGE__;
}
sub DESTROY {
$_[0]->();
}
#>>> some perl script
use DummyDestructor;
...
{
... code ...
my $final = make_finally { ... code ... } # beware!
# no access to @_ in finally
... code ...
}
A more straight-forward alternative is eval and a bare block:
sub f {
my @return;
... more code ... # vars needed in "finally" must be
# defined here!
eval{{
... and more ...
# instead of return $retval you'd need:
@return = $retval and last;
... yet more code ...
}}
... do clean up stuff here ...
die $@ if $@;
return @return;
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.