in reply to Re: Confusion over scope of "my" vars
in thread Confusion over scope of "my" vars

ups I wasn't logged in...

UPDATE: you may want to use B::Deparse and B::Concise and the debugger to see what actually happens!

Anyway I'm not sure why perl doesn't reset the lexical pad to undef when leaving the sub, might be a bug or a necessity for closures.

If I were you, I'd report this code to perlporters most likely they already discussed it!

> you can also try this, which results in an error

I know it's documented but I'm not happy about this behaviour!

  • Comment on Re^2: Confusion over scope of "my" vars

Replies are listed 'Best First'.
Re^3: Confusion over scope of "my" vars
by JavaFan (Canon) on Nov 26, 2008 at 18:24 UTC
    Anyway I'm not sure why perl doesn't reset the lexical pad to undef when leaving the sub
    Well, that's quite obvious. "Resetting" variables that go out of scope would be waste of resources. You'd spend time setting a value for a variable that has no references to it left.

    What's the point?

      > What's the point?

      Obviously the allocated space is reused, leaving it in a defined state is maybe faster and works in 99.9% of all cases but is nevertheless *dirty*.

      And an extra opcode "ResetPad" realised in C can't be too expensive in comparison to the overall overhead of function calls.

      Cheers Rolf

      UPDATES:

      1. Only if the reference counter is 0, then clearing the PAD only means supporting the garbage collection.

        (The reference counter is not neccessarily 0 at the end of the scope)

      2. hmm actually whenever the reference counter is decremented to 0 it might be the best occasion to set the variable to undefined, this would lead to a very consistent behaviour.

      3. I have to admit that some people might interpret this behaviour as a feature! I mean if noninitialised lexvars act like closuresvars, but only teh sub is in the same level of recursion! One might even calculate the level of recursions...spooky! But I bet this behaviour is not guaranteed! 8 )

        The reference counter is not neccessarily 0 at the end of the scope

        It's never zero at end of scope. At the very least, the pad references the scalar. If the refcount is one at scope exit, the variable is cleared*. If the refcount is greater than one at scope exit, a new SV is created and associated with the variable.

        * — Clearing is similar to undefining, but the string buffer isn't cleared.