in reply to Undef becomes hash reference somehow

Explanations and References to relevant information were already given by others. I would like to follow up, by an example, of how this can come back to bite you, and how you can avoid getting bitten :).
Consider the following code:
use strict; use warnings; use Data::Dumper; my %hash; if (exists $hash{foo}{bar}{element}) { print "It exists!\n" } print Dumper(\%hash);
It will output:
$VAR1 = { 'foo' => { 'bar' => {} } };
Testing for the existence of an element will autovivify all elements except for the last one, and then check whether it exists. Usually this is not the behaviour a programmer expects, when writing above code. In a more complex program with deeply nested data structure, this may created some confusion later on in the programm, since some elements will exist, even so there is no obvious reason why they should exist (until you learn about autovivification). if you want to avoid this, there is the no autovivification pragma on cpan.
use strict; use warnings; use Data::Dumper; no autovivification; # disables types of autovivification which are ty +pically not intended my %hash; if (exists $hash{foo}{bar}{element}) { print "It exists!\n" } print Dumper(\%hash);
With this one line added, the output will be as expected:
$VAR1 = {};

Replies are listed 'Best First'.
Re^2: Undef becomes hash reference somehow
by Anonymous Monk on Sep 18, 2016 at 10:15 UTC

    And to avoid the "no autovivificatio" caveats, Data::Diver :)

    use Data::Diver qw/ Dive /; if( Dive( \%hash, qw/ foo bar element /) ){ print "It exists!\n" }