Could someone point me to the specific place in the Perl docs where is guarantees that lexicals in the _same_ scope will be destroyed in LIFO order?
There is no such guarantee. In fact, it's easy to disprove.
sub DESTROY { print "Destroying $_[0][0]\n"; } { my $x = bless [ '$x' ]; my $y = bless [ '$y' ]; $x->[1] = $y; } print("\n"); { my $x = bless [ '$x' ]; my $y = bless [ '$y' ]; $y->[1] = $x; }
Destroying $x Destroying $y Destroying $y Destroying $x
What is guaranteed is that an object won't be destroyed if anything still references it. If the level 1 object contains a reference to the level 2 object, and the level 2 object contains a reference to the level 3 object, the level 1 object is guaranteed to be destroyed before the level 2 object, and the level2 object is guaranteed to be destroyed before the level 3 object.
sub DESTROY { print "Destroying $_[0][0]\n"; } { my $l3 = bless [ 'l3' ]; my $l2 = bless [ 'l2', $l3 ]; my $l1 = bless [ 'l1', $l2 ]; } print("\n"); { my $l1 = bless [ 'l1' ]; $l1->[1] = my $l2 = bless [ 'l2' ]; $l2->[1] = my $l3 = bless [ 'l3' ]; }
Destroying l1 Destroying l2 Destroying l3 Destroying l1 Destroying l2 Destroying l3
There is an exception. If variables survive until global destruction (beyond the outermost lexical scope), all bets are off. This can occur if there's a reference cycle, if it's package variable, or if it's referenced (directly or not) by a package variable.
sub DESTROY { print "Destroying $_[0][0]\n"; } my $x = bless [ '$x' ]; my $y = bless [ '$y' ]; $y->[1] = $y; # cycle our $z = bless [ '$z' ]; # pkg var END { print "Entering global destruction\n" }
$ perl a.pl Destroying $x Entering global destruction Destroying $z # Can occur in any order Destroying $y #
In reply to Re: Controlling the order of object destruction
by ikegami
in thread Controlling the order of object destruction
by metaperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |