in reply to exists() unexpected behavior

Ahh, the follies of not using strict...

These are the three crucial calls in your routine:

  1. exists $test_hash{$key1}
  2. exists $test_hash{$key1}{$key2}
  3. exists $test_hash{$key1} # again
During the first call, you test whether or not $test_hash contains a key called $key1. Of course it doesn't, so exists returns false.

During the second call, you first grab hash reference stored as a value in $test_hash with key $key. This doesn't exist, so Perl dutifully creates it for you on the fly (the behavior when you don't use strict). You then check to see if this anonymous hash contains a key equal to $key2, which it doesn't.

Since you created an anonymous hash reference on the fly in step 2, $test_hash{$key1} now contains that reference. So exists returns true.

Thus, exists() did not fill the value for $test_hash{$key1}; you implicitly did, when you did a lookup on a hash reference that previously did not exist. This would become apparent had you used strict.

The motto of the story is always use strict!

UPDATE: As MeowChow correctly points out, use strict does not catch this. Neither does -w. Oops. You should still always use strict, though :)

-Ton

-----

Be bloody, bold, and resolute; laugh to scorn
The power of man...

Replies are listed 'Best First'.
Re: Re: exists() unexpected behavior
by MeowChow (Vicar) on Apr 12, 2001 at 03:45 UTC
    Actually, this hasn't got anything at all to do with strict. Strict would not report these as errors because they are not. They are examples of a feature of Perl which, as I mentioned in my earlier node, is called autovivification.
       MeowChow                                   
                   s aamecha.s a..a\u$&owag.print