Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a hash of hashes in Perl?

Based on my current understanding of hashes in Perl, I would expect this code to print "hello world." It instead prints nothing.

%a=();

%b=();
$b{str} = "hello";  
$a{1}=%b;

$b=();
$b{str} = "world";
$a{2}=%b;

print "$a{1}{str}  $a{2}{str}"; 

I assume that a hash is just like an array, so why can't I make a hash contain another?

like image 458
Mike Avatar asked May 25 '10 21:05

Mike


3 Answers

  1. You should always use "use strict;" in your program.

  2. Use references and anonymous hashes.

use strict;use warnings;
my %a;

my %b;
$b{str} = "hello";  
$a{1}={%b};

%b=();
$b{str} = "world";
$a{2}={%b};

print "$a{1}{str}  $a{2}{str}";

{%b} creates reference to copy of hash %b. You need copy here because you empty it later.

like image 120
Alexandr Ciornii Avatar answered Oct 11 '22 12:10

Alexandr Ciornii


Hashes of hashes are tricky to get right the first time. In this case

$a{1} = { %b };
...
$a{2} = { %b };

will get you where you want to go.

See perldoc perllol for the gory details about two-dimensional data structures in Perl.

like image 6
mob Avatar answered Oct 11 '22 12:10

mob


Short answer: hash keys can only be associated with a scalar, not a hash. To do what you want, you need to use references.

Rather than re-hash (heh) how to create multi-level data structures, I suggest you read perlreftut. perlref is more complete, but it's a bit overwhelming at first.

like image 4
David Wall Avatar answered Oct 11 '22 12:10

David Wall