Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (1)
As of 2024-04-25 19:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found