Search code examples
perlhashperl-data-structures

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?


Solution

    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.