ipherian has asked for the wisdom of the Perl Monks concerning the following question:

Hi, Can anyone tell me why this happens?
use Data::Dumper qw(Dumper); $foo = undef; print Dumper($foo); # $foo is undef, obviously $bar = $foo->{bar}; print Dumper($foo); # $foo is now empty hashref

Replies are listed 'Best First'.
Re: Undef becomes hash reference somehow
by Athanasius (Archbishop) on Sep 18, 2016 at 03:11 UTC
Re: Undef becomes hash reference somehow
by Anonymous Monk on Sep 18, 2016 at 02:50 UTC
Re: Undef becomes hash reference somehow
by rminner (Chaplain) on Sep 18, 2016 at 09:14 UTC
    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 = {};

      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" }
Re: Undef becomes hash reference somehow
by Laurent_R (Canon) on Sep 18, 2016 at 07:51 UTC
    This is not directly related with the autovivication issue you're experiencing, but please note that your program would not even compile using the following:
    use strict; use warnings;
    because $foo and $bar haven't been properly declared.

    You should really use these pragmas for all your programs, except possibly one-liners. They let the compiler help you preventing many mistakes.