If you want to avoid autovivification, there's the autovivification module. It allows you to disable autovivification for a particular scope. Example:

use 5.010; use strict; use Data::Dumper; my %rec; { no autovivification; say "Oh No!(1)" if exists $rec{NOTE}{Nested}; say "Oh No!(2)" if exists $rec{NOTE}; } say "Oh No!(3)" if exists $rec{NOTE2}{Nested}; say "Oh No!(4)" if exists $rec{NOTE2}; print Dumper \%rec; __END__ Oh No!(4) $VAR1 = { 'NOTE2' => {} };

It even allows you to selectively disable it - e.g. disable autovivification for "exists", but not when storing a new value.

no autovivification qw(exists); if (!exists $rec{NOTE}{Nested}) { # but this still autovivifies $rec{NOTE}={}; $rec{NOTE}{Nested2} = 'Foo'; }

And also allows you to make autovivification warn or die.

perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

In reply to Re: gotchas with hash element autovivification by tobyink
in thread gotchas with hash element autovivification by raybies

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.