in reply to gotchas with hash element autovivification

Are there conditions in which you can still create autovivified hash keys with undefined values that you never intended to do? And what is the way to avoid that now with current versions of Perl?
Nothing has changed in this aspect in the 21st century. $rec{NOTE} did not autovivify in 5.005, and it doesn't in 5.15.9. exists $rec{NOTE}{Nested} autovivified $rec{NOTE} in 5.005, and it does so in 5.15.9.

It probably wasn't different pre-5.005, but I don't have such a perl currently available.

If you want to avoid it? Use long hand:

if ($rec{NOTE} && exists $rec{NOTE}{Nested}) { ... }

Replies are listed 'Best First'.
Re^2: gotchas with hash element autovivification (dry)
by tye (Sage) on Apr 03, 2012 at 01:28 UTC
    if ($rec{NOTE­} && exists $rec{NOTE}­{Nested}) {

    More-DRY versions:

    if( exists ${ $rec{NOTE­} || {} }{Nested} ) { # or if( ( $rec{NOTE­} || {} )->{Nested} ) { # or if( exist +( $rec{NOTE­} || {} )->{Nested} ) {

    Though, I find that I use those less often to avoid auto-viv and more often to prevent a potential fatal "Can't use undef as HASH ref" (something that I think should at least be turned into just a warning -- since sometimes it is fatal and sometimes it is a silent success, and I'm not even sure what distinguishes between those two behaviors).

    - tye        

      It's a matter of opinion, but I prefer the simplicity of my suggestion, even if there's repetition. Even though I sometimes use your technique (typically in cases like keys %{$hash{foo} || {}}), I still had to look twice.