in reply to Re^5: Common hash keys
in thread Common hash keys

The exists test is so that the case where a key has undef as a value, not to aviode auto vivification. Undef itself cannot be a key in a hash. But '0' and '' can.

Replies are listed 'Best First'.
Re^7: Common hash keys
by Porculus (Hermit) on Jun 15, 2008 at 17:30 UTC

    I've seen this "use exists() to avoid autovivification" misconception around a lot. I suspect it comes from this statement in exists:

    The element is not autovivified if it doesn’t exist.

    Other similar functions like defined don't have any such statement, leading people to believe that those somehow do autovivify elements, which in turn leads to unnecessarily complicated code like

      my $foo_in_hash = exists $hash{foo} && defined $hash{foo};

    I'm not sure why that disclaimer is there in the first place. Surely it's never meaningful to talk about autovivifying elements, since autovivification is about the silent creation of actual hashes and arrays, not their contents? And this also leads some people to think exists doesn't autovivify things at all, which it certainly does (as indeed the documentation goes on to explain... but some people never read past the first paragraph!)

    This is one of those little nitpicks I'm often tempted to submit a bug report about, but I'm never quite convinced it's really serious enough to warrant it. (And I'm not 100% confident it's wrong! I'm painfully conscious there's still a heck of a lot left for me to learn about Perl.)