Because of autovivification-related bugs, I got into the habit of using defined instead of exists to determine whether a hash contains a certain key.

Back up one second there. exists exists in Perl's vocabulary for the purpose of determining if a hash element exists. defined doesn't tell you whether or not it exists, it tells you whether or not it has a value set.

The autovivication problem doesn't occur when you do this:

print "Exists!\n" if exists $hash{somekey};

It occurs when you do something like this:

my %hash = ( Key1 => { john => 1, pete => 2 }, Key2 => { frank => 3, howard => 4 } ); print "ted Exists!\n" if exists $hash{Key7}{ted}; print "Key7 now exists!\n" if exists $hash{Key7};

The difference is that in order to test for the existance of ted as an element referenced by $hash{Key7} Perl has to autovivify Key7. That is a big difference. The moral of the story is to always check for the existance of the higher level (if you cannot assume it exists) before checking for the existance of the lower level. But that's no reason to resort to using defined to do exists job, and in fact, using defined in this sort of context isn't going to prevent autovivication since testing for ted's value still requires that Key7 spring into existance silently.

To that point, the "autovivication bugs" issue is not a bug in exists, it's a type of bug that programmers encounter by not understanding how autovivication works.


Dave


In reply to Re^2: need explanation of @foo{@bar} = (); (hash slice) by davido
in thread need explanation of @foo{@bar} = (); (hash slice) by Anonymous Monk

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.