in reply to coderefs keep references to themselves

Actually its the other way round; the destroy doesn't happen because its not a closure. For non-closure anonymous subs, perl just shares the same internal CV structure among all the code refs to the sub

As soon as you make the sub a closure (by referring to an external lexical var), it starts to behave the way you expect:

$ perl -e 'my $z; my $x = sub { $z; "test" }; bless $x, "HRM"; sub HR +M::DESTROY { print "bye\n" };' bye $

Dave.

Replies are listed 'Best First'.
Re^2: coderefs keep references to themselves
by jettero (Monsignor) on Jul 15, 2008 at 12:02 UTC
    Curious. I definitely don't understand how using $z in $x makes $x point to $x less.

    -Paul

      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.