Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a hash in a hash

Tags:

hash

perl

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)

like image 512
cruppstahl Avatar asked Jul 03 '11 20:07

cruppstahl


People also ask

Can a hash be undone?

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.

How do you store items in a hash table?

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.

What is storage hash?

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.


1 Answers

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.

like image 109
Flimzy Avatar answered Nov 09 '22 09:11

Flimzy