in reply to Re^4: Looping through a hash reference is creating a key...?
in thread Looping through a hash reference is creating a key...?

I have to wonder if exists could be patched to not have this behavior. Short-circuiting comes to mind.
It wouldn't be easy. By the time the exists op is called, all but one of the derefs has already taken place. IE exists is essentially a binary operator taking a hash and key as args:
exists $hash{a}{b}{c}
is executed as:
exists(%{$hash{a}{b}}, 'c')

Dave.

Replies are listed 'Best First'.
Exists and autovivification (was: Looping through a hash reference...)
by Roy Johnson (Monsignor) on Jun 12, 2004 at 01:12 UTC
    It shouldn't be particular to exists(), it should be a general rule: autovivification should only happen to lvalues. When non-lvalues are evaluated, they short-circuit as soon as they encounter an undefined component, and return undef. exists() naturally returns false when checking a component of an undef (e.g., your latter example evaluates as exists(undef, 'c')).

    Of course, there's probably some code by now that relies on autovivification of non-lvalues, and that argues strongly against implementing this suggestion. I can't think of any other arguments against it, though doubtless someone else can.


    We're not really tightening our belts, it just feels that way because we're getting fatter.
      Code such as
      $bazref = \$foo{bar}{baz}
      too relies on autovivification.
        Good point. Taking a reference of anything would have to autovivify it.

        We're not really tightening our belts, it just feels that way because we're getting fatter.

        Taking a reference is an "lvalue context". So this isn't an exception but part of the same rule. Even in C, you can't take the address of a non-lvalue (it might be 'const' aka 'read-only', of course).

        The $hash{key1}{key2} autovification of 'key1' has long been considered a minor bug. So I'd hope that backward compatability to bugs isn't a good reason to a prevent fixing them.

        - tye