Chapter 10. Object Destruction

In the previous two chapters, we looked at basic object creation and manipulation. In this chapter, we’ll look at an equally important topic: what happens when objects go away.

As you saw in Chapter 4, when the last reference to a Perl data structure goes away, Perl automatically reclaims the memory of that data structure, including destroying any links to other data. Of course, that in turn may cause other (“contained”) structures to be destroyed as well.

By default, objects work in this manner because objects use the same reference structure to make more complex objects. An object built of a hash reference is destroyed when the last reference to that hash goes away. If the values of the hash elements are also references, they’re similarly removed, possibly causing further destruction.

Suppose an object uses a temporary file to hold data that won’t fit entirely in memory. The filehandle for this temporary file can be included as one of the object’s instance variables. While the normal object destruction sequence will properly close the handle, you still have the temporary file on disk unless you take further action.

To perform the proper cleanup operations when an object is destroyed, you need to be notified when that happens. Thankfully, Perl provides such notification upon request. You can request this notification by giving the object a DESTROY method.

When the last reference to an object, say $bessie, is destroyed, Perl invokes:

$bessie->DESTROY ...

Get Learning Perl Objects, References, and Modules now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.