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

I must disagree. Having two variables or functions with the same name in the same scope is a bad idea.

There is no big point for using nested subs if they are not completely encapsulated

Some encapsulation is better than no encapsulation. The extra complications are not needed. Even with the extra complications, it's still not completely encapsulated.

# No Memory Leak!

You haven't changed anything. $inner still refers to the sub. The sub still captures $inner if the helper was recursive. The potential for a memory leak hasn't changed at all. You made it more complex for no gain.Eventually, $inner will be assigned a new value and stop referring to the helper. Nevermind.

Replies are listed 'Best First'.
Re^8: sub fuction inside sub functioin?
by LanX (Saint) on Dec 08, 2008 at 02:56 UTC
    why should a recursive call of inner() do a memory leak with a lexical but not with a packagevar?

    Cheers Rolf

      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.

        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