| [reply] |
Hi, Its called autovivification
If you treat empty scalar as a hash reference, it becomes a hash reference
$ perl -e" $_->{yo}=1; $_->[2]=2; "
Not an ARRAY reference at -e line 1.
perldata, perlref, Modern Perl page 60 , Data::Diver for convenience over autovivification | [reply] [d/l] |
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 = {};
| [reply] [d/l] [select] |
use Data::Diver qw/ Dive /;
if( Dive( \%hash, qw/ foo bar element /) ){
print "It exists!\n"
}
| [reply] [d/l] |
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.
| [reply] [d/l] |