Skip to Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

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 applies only 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.
Start your free trial

You might also like

Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata