develooper Front page | perl.perl5.porters | Postings from May 2012

[perl #47027] Documentation: BEGIN, END docs in wrong section

Thread Previous | Thread Next
From:
bulk 88 via RT
Date:
May 4, 2012 18:57
Subject:
[perl #47027] Documentation: BEGIN, END docs in wrong section
Message ID:
rt-3.6.HEAD-4610-1336183045-732.47027-15-0@perl.org
On Fri May 04 09:23:17 2012, tom christiansen wrote:
> That's not quite true.  
> 
> Things like UNITCHECK and END are used as per-module
> setup and cleanup code that are called implicitly; hence
> the all-caps.  This makes for more robust module design
> that making people call mod_setup() and mod_cleanup()
> type functions, which they might forget to do.
> 
> END works as a classwide destructor, just as DESTROY
> works as a per-object destructor.
> 
> So I disagree that those functions have nothing to 
> do with modules.

Although textbook usage of the BEGIN/END blocks is with modules, there
is no reason to only use them with modules. Here is an example of the
END block, no packages, no modules, no symbol table, no blessed objects.
______________________________________
use strict;
use warnings;
sub createHandle {
    return int(rand(5999))+1;
}
sub destroyHandle{
    my $handle = shift;
    die "handle is invalid" if $handle > 6000 || $handle < 0;
    print "handle destroyed\n";
}
my $newHandle = createHandle();
die "time to die";
END{
    if($newHandle) {destroyHandle($newHandle);}
}
________________________________________
If I want to clean up resources in Perl on a die/croak, and don't want
to write a class, which is 1-3 (OOP ones) very challanging PODs (for a
beginner) which a user must read, the simplest thing is to use an END
block. An END block is much easier for a beginning Perl programmer to
use than making a package, writing a new sub (includes choosing whether
to bless a scalar, a hash, or an array, or more!), writing a DESTROY
sub, switch back to main package, and creating an instance of the class,
and repeat the previous steps  half a dozen times. With END they can use
die without having to call a C-ish destructor sub before each die
statement in their code.

Sorry if this reply appears twice.

---
via perlbug:  queue: perl5 status: open
https://rt.perl.org:443/rt3/Ticket/Display.html?id=47027

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About