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...


In reply to Re: exists() unexpected behavior by ton
in thread exists() unexpected behavior by Richard

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.