I'm having troubles with a Perl script. I try to store a hash in a hash. The script is trivial:
use Data::Dumper;
my %h1=();
$h1{name}="parent";
my %h2=();
$h2{name}="child";
$h1{nested}=%h2; # store hash h2 in hash h1
print "h2:\n";
print Dumper(%h2); # works
print "h1{nested}:\n";
print Dumper($h1{nested}); # fails
The results:
h2:
$VAR1 = 'name';
$VAR2 = 'child';
h1{nested}:
$VAR1 = '1/8';
Why is the $h1{nested} not dumped as a hash, but as some kind of weird scalar (1/8)?
PS: even if this question sounds trivial - I searched SO but did not find that it was asked before. PPS: my Perl is v5.10.1 (*) built for x86_64-linux-gnu-thread-multi (with 53 registered patches, see perl -V for more detail)
Hash functions are not reversible in general. MD5 is a 128-bit hash, and so it maps any string, no matter how long, into 128 bits. Obviously if you run all strings of length, say, 129 bits, some of them have to hash to the same value.
To store an element in the hash table you must insert it into a specific linked list. If there is any collision (i.e. two different elements have same hash value) then store both the elements in the same linked list. The cost of a lookup is that of scanning the entries of the selected linked list for the required key.
Hash Storage Structure. Hash is the keyed storage structure that calculates a placement number or address by applying a hashing algorithm to the key data value. A hashing algorithm is a function that does mathematical computations to a piece of data to produce a number.
You can only store a hashref in a hash:
$h1{nested}=\%h2;
and then you would access %h2
's name by doing
$h1{nested}->{name}
In your code, %h2 is forced to scalar context, which shows you that "1/8" value, and stores that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With