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

Good point. I remember finding that out the hard way when I wrote some code that did exists() checks on deeply nested nodes in a huge data structure. My exists checks made the structure grow about 10MB in memory! Adding uglier but more careful code (if (exists $h{1} && exists $h{1}->{2} && exists ...) made the problem go away.

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

      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.