Destroying an Object

Problem

You want to run special code whenever an object is no longer used. This is sometimes needed when the object is an interface to the outside world—or contains circular data structures— and must clean up after itself. You might remove temporary files, break circular links, gracefully disconnect from a socket, or kill a spawned subprocess.

Solution

Create a method named DESTROY. This will be called when there are no more references to the object, or else when the program shuts down, whichever comes first. You don’t need to do any memory deallocation here, just any finalization code if it makes sense for the class.

sub DESTROY {
    my $self = shift;
    printf("$self dying at %s\n", scalar localtime);
}

Discussion

Every story has a beginning and an end. The beginning of the object’s story is its constructor, explicitly called when the object comes into existence. The end of its story is the destructor, a method implicitly called when an object leaves this life. Any per-object clean-up code is placed in the destructor, which must be named DESTROY.

Why can’t destructors have arbitrary names? Because, although a constructor is explicitly called by name, a destructor is not. Destruction happens automatically via Perl’s garbage collection (GC) system, which is currently implemented as a quick but lazy reference-based GC system. To know what to call, Perl insists that the destructor be named DESTROY. If more than one object goes out of scope at once, Perl doesn’t promise ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.