Can some one help me understand the output of this Perl program:
use Data::Dumper;
my %hash;
$hash{hello} = "foo";
$hash{hello}{world} = "bar";
print $hash{hello} . "\n";
print $hash{hello}{world} . "\n";
print Dumper(\%hash);
And the output:
foo
bar
$VAR1 = {
'hello' => 'foo'
};
Where is the “foo” coming from? How come it isn’t printed out by dumper?
Note that if I swap the order of the assignments:
use Data::Dumper;
my %hash;
$hash{hello}{world} = "bar";
$hash{hello} = "foo";
print $hash{hello} . "\n";
print $hash{hello}{world} . "\n";
print Dumper(\%hash);
my output is what I expect:
foo
$VAR1 = {
'hello' => 'foo'
};
EDIT:
I know that use strict; would catch this, but I’m more interested in know how the string “foo” is still being printed.
Your code is missing
C:\Temp> hui Can't use string ("foo") as a HASH ref while "strict refs" in use at C:\Temp\hui.pl line 7.Make sure all your scripts start with:
Given:
$hash{hello}is NOT a hash reference.treats the string
"foo"as a hash reference and creates the hash%main::fooand sets$foo{world}to"bar".When you do:
it only prints the contents of
%hash. Whereas, when you doit prints
$foo{world}.Without
strict, you do not get to find out that the script has trampled all over the package name space.Add a
or
to inspect the symbol table after you run this.