note
ambrus
<p>
<c>sub {}</c> 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.
<c>
perl -we 'sub f { sub { } }; $x = f(); $y = f(); warn "$x $y";'
</c>
<p>
In comparision, if you get a reference with an array or hash constructor <c>[]</c> or <c>{}</c>, or with a lexical variable like <c>do {\my $t}</c> or <c>do {\my @a}</c>, you always get a fresh one because arrays and hashes are mutable.
<p>
<b>Update:</b> 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.
<c>
perl -we 'sub f { my $t; sub { $t } }; $x = f(); $y = f(); warn "$x $y";'
</c>
818955
818955