Skip to Content
Intermediate Perl, 2nd Edition
book

Intermediate Perl, 2nd Edition

by Randal L. Schwartz, brian d foy, Tom Phoenix
July 2012
Intermediate to advanced
396 pages
9h 16m
English
O'Reilly Media, Inc.
Content preview from Intermediate Perl, 2nd Edition

Chapter 18. Object Destruction

In Chapters 13 and 15, 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. In Perl, we call the process of cleaning up an object destroying it.

As we showed in Chapter 5, 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 Perl to destroy other (“contained”) structures as well.

By default, objects work in this manner because objects use the same reference-count–based garbage collection to make more complex objects. Perl destroys an object built with a hash reference when the last reference to that hash goes away. If hash values are also references, they’re similarly removed, possibly causing further destruction.

Cleaning Up After Ourselves

Suppose our object uses a temporary file to hold data that doesn’t fit entirely in memory. The object can include a filehandle to a temporary file in its instance data. While the normal object destruction sequence will properly close the handle, we still have the temporary file on disk unless we take further action.

To do the proper cleanup operations when Perl destroys an object, we need to know when that happens. Thankfully, Perl provides such notification upon request. We can request this notification by giving the object a DESTROY method.

When the last reference to 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

Mastering Perl, 2nd Edition

Mastering Perl, 2nd Edition

brian d foy
Perl & LWP

Perl & LWP

Sean M. Burke
Advanced Perl Programming

Advanced Perl Programming

Sriram Srinivasan

Publisher Resources

ISBN: 9781449343781Errata Page