http://www.perlmonks.org?node_id=1020940


in reply to Re: when is destroy function called
in thread when is destroy function called

Maybe this is helpful?

I don't think your first example helps answer the op's question. Did the gc destroy the objects immediately after you undefined $head or did the gc merely mark them as ready for destruction, and then when the program ended the memory was released?

Some evidence from "Intermediate Perl (2nd)", p. 257:

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, say $bessie, disappears, Perl invokes that object’s DESTROY method automatically, *as if we had called it ourselves*:

$bessie−>DESTROY

This method call is like most other method calls: Perl starts at the class of the object and works its way up the inheritance hierarchy until it finds a suitable method. However, unlike most other method calls, there’s no error if Perl doesn’t find a suitable method.

That suggests that DESTROY is called immediately after the reference count goes to 0--in other words the object is not merely marked for destruction with DESTROY being called at the gc's leisure.