You're partly correct. In the case of this example, where there is only a single level hash, exists will not autovivify the key. However, if this was a complex data structure containing a HoH, HoA, AoH, etc, then the intermediate references (but not the terminal reference) would be autovivified*. To avoid autovivifying the intermediate structures you have to use exists to check each one as you go, or use something like tye's Data::Diver. See the example below.

use strict; use warnings; use Data::Diver qw( Dive ); use Data::Dumper; my %h; # The exists function will autovivify intermediate keys print "Testing with exists\n"; printf "key1 %s exist\n", exists $h{key1} ? 'does' : 'does not'; printf "key1-key2 %s exist\n", exists $h{key1}{key2} ? 'does' : 'does +not'; printf "key1 %s exist\n", exists $h{key1} ? 'does' : 'does not'; print Dumper( \%h ); # Data::Diver's Dive will not autovivify intermediate keys print "\nTesting with Data::Diver\n"; my @values = Dive ( \%h, 'key3', 'key4' ); printf "key3-key4 %s exist\n", @values ? 'does' : 'does not'; print Dumper( \%h );
Output:
Testing with exists key1 does not exist key1-key2 does not exist key1 does exist $VAR1 = { 'key1' => {} }; Testing with Data::Diver key3-key4 does not exist $VAR1 = { 'key1' => {} };

*You may know this, but someone else reading your reply may not realize the difference in behavior for single level vs multi level structures.


In reply to Re^3: What protects me from doing this stupid thing..? (autovivification) by bobf
in thread What protects me from doing this stupid thing..? by Cody Pendant

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.