4.3.4. The Destructor

A destructor is a special method that is called whenever the instance of the class goes out of scope. To define a destructor in Perl just define a method by the name of DESTROY.

To demonstrate it, I present a class derived from Bar2 that prints the number of times it's name was assigned to the screen before it is destroyed:

package Count;

use strict;
use warnings;

use vars qw(@ISA);

use Bar2;

@ISA=qw(Bar2);

sub DESTROY
{
    my $self = shift;

    print "My name was assigned " . $self->get_num_times_assigned() . " times.\n";
}

1;

Written by Shlomi Fish