in reply to Re^2: coderefs keep references to themselves
in thread coderefs keep references to themselves

It's because there's a reference to a variable in the enclosing scope ($z) that it's actually now a closure. Before it had no ties to any variables in the enclosing scope so it wasn't a closure triggering the optimization. Adding $z means that it now does reference a var in the enclosing scope and won't trigger the optimization and now the destructor is called. If yours (or his) had referenced $x (although you'd have to make the declaration and assignments two steps (e.g. my $x; $x = sub { $x; "test" })) then $x would have served the same purpose; as is $x never enters into the closure/not-closure picture because your lexical $x isn't referenced from your anonymous sub.

The cake is a lie.
The cake is a lie.
The cake is a lie.