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

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?

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

Replies are listed 'Best First'.
Re^4: Confusion over scope of "my" vars
by LanX (Saint) on Nov 26, 2008 at 18:31 UTC
    > 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.

        I'm sure the behaviour is well defined and consistent and well thought and I'm trusting it ... but if you say:

        > If the refcount is one at scope exit, the variable is cleared*

        aren't you denying the results of the OT? The scope of the sub is left, only the reference of the pad should be left, but the variable isn't cleared?

        anyway I remember Advanced Perl Programming having a detailed explanation about pads and refcounts. So if you think you don't have a typo in your last post, don't bother explaining to me, what I can easily look up in detail in my bookshelf ... 8 )

        Cheers Rolf