in reply to HoH Weirdness
You are actually creating a symbolic reference, creating a new hash named "Apple" in the case of:
$hash{'food'} = 'Apple'; $hash{'food'}{'color'} = 'Red'; print "$hash{food}{color}\n"; print "$Apple{color}\n";
This might be more apparent if you look at the dereference in this manner:
$hash{'food'} = 'Apple'; ${$hash{'food'}}{'color'} = 'Red'; print "$hash{food}{color}\n"; print "$Apple{color}\n";
You can see that you are using a string as a reference. However, in the following situation:
$hash{food}{color} = 'Red'; $hash{food} = 'Apple';
Because $hash{food} is undefined, Perl autovivifies the hash reference and stores it as the value for the key 'food'. The next line simply overwrites that value with the string 'Apple'. The key is knowing that Perl only autovivifies when you dereference an undefined value as a reference. Then we get to your final example:
$hash1{'food'} = 'Apple'; $hash1{'food'}{'color'} = 'Red'; $hash2{'food'}{'color'} = 'Red'; $hash2{'food'} = 'Apple'; print "hash1: $hash1{'food'}{'color'} $hash1{'food'}\n"; print "hash2: $hash2{'food'}{'color'} $hash2{'food'}\n";
And one hash is mysteriously affecting another --- but really, your the second statement result in a symbolic reference to a hash %Apple with a key 'color' and value 'Red'. The first hash2 assignment does autovivify a real hash reference, but that is overwritten in the second hash2 assignment. When you print out hash2, the first value is actually dereferencing the symbolic %Apple hash, just like before. This kind of confusion is a good reason to *not* use symbolic references and to always use 'strict'.
|
|---|