in reply to Re^3: 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. If $h{1} doesn't exist, $h{1}{2} certainly won't. I'd look at it, but I can't code my way out of a paper bag in C. Plus, I have to believe that I'm not the first person to come up with such a notion.

Just a thought,
thor

  • Comment on Re^4: Looping through a hash reference is creating a key...?

Replies are listed 'Best First'.
Re^5: Looping through a hash reference is creating a key...?
by dave_the_m (Monsignor) on Jun 10, 2004 at 22:36 UTC
    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.

      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.