in reply to gotchas with hash element autovivification
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.
|
---|