- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

16.7 Destructors

When the last reference to an object goes away, the object is automatically destroyed. (This may even be after you exit, if you've stored references in global variables.) If you want to capture control just before the object is freed, you may define a DESTROY method in your class. It will automatically be called at the appropriate moment, and you can do any extra cleanup you need to do. Perl passes a reference to the object under destruction as the first (and only) argument. Beware that the reference is a read-only value, and cannot be modified by manipulating $_[0] within the destructor. The object itself (i.e. the thingy the reference points to, namely ${$_[0]}, @{$_[0]}, %{$_[0]} etc.) is not similarly constrained.

Since DESTROY methods can be called at unpredictable times, it is important that you localise any global variables that the method may update. In particular, localise $@ if you use eval {} and localise $? if you use system or backticks.

If you arrange to re-bless the reference before the destructor returns, perl will again call the DESTROY method for the re-blessed object after the current one returns. This can be used for clean delegation of object destruction, or for ensuring that destructors in the base classes of your choosing get called. Explicitly calling DESTROY is also possible, but is usually never needed.

DESTROY is subject to AUTOLOAD lookup, just like any other method. Hence, if your class has an AUTOLOAD method, but does not need any DESTROY actions, you probably want to provide a DESTROY method anyway, to prevent an expensive call to AUTOLOAD each time an object is freed. As this technique makes empty DESTROY methods common, the implementation is optimised so that a DESTROY method that is an empty or constant subroutine, and hence could have no side effects anyway, is not actually called.

Do not confuse the previous discussion with how objects CONTAINED in the current one are destroyed. Such objects will be freed and destroyed automatically when the current object is freed, provided no other references to them exist elsewhere.

ISBN 9781906966027Perl Language Reference ManualSee the print edition