If you were using strict, you would see why the results from your second program is different from those of the first.
C:\test>type test.pl #! perl -slw use strict; use Data::Dumper; my %hash; $hash{keya} = ""; $hash{keyb} = ""; $hash{keyc} = ""; $hash{keya}{1} = "fooA"; $hash{keya}{2} = "barA"; $hash{keyb}{1} = "fooB"; $hash{keyb}{2} = "barB"; $hash{keyc}{1} = "fooC"; $hash{keyc}{2} = "barC"; print Dumper (\%hash); C:\test>test Can't use string ("") as a HASH ref while "strict refs" in use at C:\t +est\test.pl line 11.
In the first program, when you initialise the keys keya, keyb, and keyc in the %hash, you are implicitly initialising them to undef.
In the second program, you are explicitly initialising them to a null string "".
In the first, when you do
$hash{keya}{1} = "fooA";
you are attempting to assign a value to the key 1, in the anonymous hash that is pointed at by the reference held in the keya element of %hash, which doesn't exist! Whilst keya exists, it is set to undef.
Seeing this, the compiler does the DWIM that perl does so well, and decides to autovivify (create implicitly), an anonymous hash, with a key of 1, assign "fooA" to that key, and then assign a reference to that anonymous hash as the value of $hash{keya}.
Result: It did what you thought it would do, even though it did much more than you probably thought in order to do it.
However, in the second program, when perl encounters the same line, it discovers that not only does the keya key exists in %hash, but that the value of that key is already set (to a null string).
At this point, it knows that it can neither use that null string as a reference to an anonymous hash (hence the error listed under strict) nor can it legitimately overwrite the null string with a reference to an anonymous hash as that would be implicitly destroying the value that you had explicitly assigned.
With strict enabled, it not only refuses to overwrite your explicitly assigned data, it yells that it has done so.
Without strict, it still doesn't do the assignment, but just doesn't say anything. You didn't ask it to tell you, so it assumes that you know what you are doing and keeps stum.
The net result is that in the second program, lines 6 through 11 do absolutely nothing.
In reply to Re: Re: Re: Hash and Array
by BrowserUk
in thread Hash and Array
by donno20
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |