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


in reply to when is destroy function called

Perl is reference counted. So unless you're writing XS or creating circular references, you don't need to pay much attention. However, for those times when you do... the destructor is called when the last reference is undefined.

the following...

package Dalek;
sub new { return bless {}; }
sub exterminate { return q{'exterminate'}; }
sub obey { return q{'obey'}; }
sub DESTROY { print "destroy\n"; }

package main;
my $obj = Dalek->new();
print "obj is a: ", ref($obj), "\n";
print "Where's my ", eval('$obj->obey()'), undef($obj), eval('$obj->exterminate()'), " spanner?\n";
print $@ if $@;

gives...

> perl destroy.pl
obj is a: Dalek
Where's my 'obey' spanner?
destroy
Can't call method "exterminate" on an undefined value at (eval 2) line 1.

Note that the object is destroyed before the print statement in the destructor is flushed to STDOUT