Instance Destructors
As with any other referent in Perl, when the last reference to an object
goes away, its memory is implicitly recycled. With an object, you have the
opportunity to capture control just as this is about to happen by defining
a DESTROY subroutine in the class’s
package. This method is triggered automatically at the appropriate moment,
with the about-to-be-recycled object as its only argument.
Destructors are rarely needed in Perl because memory management is handled automatically for you. Some objects, though, may have state outside the memory system that you’d like to attend to, such as filehandles or database connections.
package MailNotify;
sub DESTROY {
my $self = shift;
my $fh = $self–>{mailhandle};
my $id = $self–>{name};
print $fh "\n$id is signing off at " . localtime() . "\n";
close $fh; # close pipe to mailer
}Just as Perl uses only a single method to construct an object, even
when the constructor’s class inherits from one or more other classes, Perl
also uses only one DESTROY method per
object destroyed regardless of inheritance. In other words, Perl does not
do hierarchical destruction for you. If your class overrides a
superclass’s destructor, then your DESTROY method may need to invoke the DESTROY method for any applicable base
classes:
sub DESTROY {
my $self = shift;
# check for an overridden destructor...
$self–>SUPER::DESTROY if $self–>can("SUPER::DESTROY");
# now do your own thing before or after
}This only applies to inherited classes; an object ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access