in reply to Referencing localized variables, and typeglobs

Concerning your first question, the output you get is exactly what I was expecting when reading the code. While I can't really think of any use for such a strange construct, clearly the local keyword modifies the hash to be "local" to the enclosing do block. So that the code populates each time a local copy of %h and retrieves a reference to this local copy of the hash and assigns this reference to $x and $y. As soon as the code leaves the do block, the value of the hash is reset to its original empty value.

I may be wrong, but I can't see why it wouldn't be safe to do that. And I don't even think it is magic.

Or did I perhaps miss something about your concerns?

Replies are listed 'Best First'.
Re^2: Referencing localized variables, and typeglobs
by haukex (Archbishop) on Aug 30, 2017 at 21:07 UTC

    Thanks for the reply! My main concern is that I haven't yet found a description of the behavior in the perldocs or (so far) elsewhere.

    So while you are right that the behavior does seem logical, there is another possible interpretation of the code: One might expect that after the effects of the local are over, $x and $y could refer back to the original %h, instead of some anonymous hashes. I'm not saying this interpretation is better or worse than the actual behavior, just that it'd be nice if it were documented.

    Another concern is that perlsub says "This operator works by saving the current values of those variables in its argument list on a hidden stack and restoring them upon exiting the block, subroutine, or eval." - So the values are saved on a stack and presumably the temporary value is popped back off when the scope exits. Without some reassurance from the docs, one might worry that the temporary variables might somehow "go away" when the scope exits (e.g. is this stack refcounted?) and a reference to such a value might become invalid (however unreasonable or not the worry might be).

      One might expect that after the effects of the local are over, $x and $y could refer back to the original %h,
      Why should it? $x and $y are assigned to the value returned by the do block. And this value happens to be an anonymous hash ref produced within the block. And $x does not know anything about the %h hash. The fact that %h is restored to an empty hash immediately thereafter is irrelevant to the value acquired by $x at the time of the assignment.

      Well, I understand your concern, but I do not think there is any reason to worry here. I think the behavior is quite clear.