in reply to Re^8: sub fuction inside sub functioin?
in thread sub fuction inside sub functioin?

Lexicals are captured (counts as a reference), but package variables are not.

When using a lexical var, the var refers to the helper and the helper refers to the var via its pad. A cyclic reference exists.

When using a package var, the var refers to the helper but the helper doesn't refer to the var. It finds it via its symbol name when it's needed. No cyclic reference exists.

And no, exiting the scope isn't sufficient to break the cycle. Seeing two references to $inner (outer's and inner's pads) when inner exits, inner creates a new SV and aliases $inner to it. The SV still exists anonymously since outer's pad still refers to it.

  • Comment on Re^9: sub fuction inside sub functioin?

Replies are listed 'Best First'.
Re^10: sub fuction inside sub functioin?
by LanX (Saint) on Dec 08, 2008 at 11:10 UTC
    I don't get it!

    In my example the lexical variable $inner is allocated *once* in the outer-closure. You may have plenty of cyclic refrences, but please show me how the allocated space for this *lonely* variable may cause a memory leak!?!

    or do you think the space for the reference counter may leak???

    Cheers Rolf

      Are you talking about the original lexical code (sub outer { my $inner; ... }) or the updated one ({ my $inner; sub outer { ... } }). I sent you a message a few posts ago that I updated my post to retract my comment.
        I was talking about
        { my $inner; sub outer { $inner=sub { ... $inner->(); ... } } }.
        OK I just saw your update. IMHO this is the safest way to realize inner subs without stash side-effects and cyclic memory leaks.

        To get back to the OT, I recommend it this way.

        Cheers Rolf