http://qs1969.pair.com?node_id=818958


in reply to No DESTROY object.

sub {} does not refer to any lexical variables, so it is optimized to always return a reference to the same sub, instead of creating subs every time. Thus, that sub is never destroyed. For example, see that this prints the same address twice.

perl -we 'sub f { sub { } }; $x = f(); $y = f(); warn "$x $y";'

In comparision, if you get a reference with an array or hash constructor [] or {}, or with a lexical variable like do {\my $t} or do {\my @a}, you always get a fresh one because arrays and hashes are mutable.

Update: sorry, originally I posted the wrong example code, the one that shows when the sub does refer to a lexical variable, so the two calls to f returned subs that referred to two different variables, thus, the addresses were different. It's now corrected above, below is that old code.

perl -we 'sub f { my $t; sub { $t } }; $x = f(); $y = f(); warn "$x $y +";'