http://www.perlmonks.org?node_id=8179

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Replies are listed 'Best First'.
Re: How do I make a destructor?
by chromatic (Archbishop) on Apr 20, 2000 at 20:56 UTC
    Create a method named DESTROY. As in other languages, if you need to close a filehandle, clean up a temporary file, release some resource, or break a circular reference, here is where you do it. Perl will call an object's DESTROY method when the object goes out of scope, right before it is garbage collected. Usually, it isn't necessary to define your own, but in the interest of completeness:
    package CowboyNeal; sub DESTROY { my $self = shift; print ref($self), " is going away. It was known as ", $self->name +(), " back in the day.\n"; }
    This would be more useful if CowboyNeals were circular lists that needed to be broken, as in this case:
    sub DESTROY { my $self = shift; $self->{first} = undef; $self->{last} = undef; }
    But that's just downright nutty.
Re: How do I make a destructor?
by nite_man (Deacon) on Feb 10, 2003 at 08:48 UTC
    You can create a descructor like this:
    sub DESTROY{ my $self = shift; $self->coun_decr(); bless $self, $ISA[0]; }
    But before, you should define a object counter and methods for management it:
    my $inst_count = 0; sub get_inst_count { $inst_count } sub _incr_inst_count { ++$inst_count } sub _decr_inst_count { --$inst_count }