Search code examples
perlperl-data-structures

Hashes of Hashes with array values


I am trying to generate a hash using hashes of hashes with array values concept. I am not sure if my syntax is right.

Below is the code section that I am hoping should create hashes of hashes with array values.

 use strict;
 %hash=();
 open IN, "samplefile.txt" or die "cannot open file:$!"; 
 while(<IN>){
     chomp $_;
     my @split=split("\t", $_);
     $hash{$split[0]}{$split[1]}=push @{ $hash{$split[0]}{$split[1]} },$split[2];
     push(@array, $split[1]);
  }

Sample dataset:

4 10 2
9 4 3
4 3 2
4 3 8
4 10 5
4 5 2

Expected hash.

%hash=(
    '4'=> {
    '10'=>'2, 5'
     '5' => '2'
     '3' => '2,8'
   }
 '9'=>{
     '4'=>'3'
 }
)

Solution

  • I think you actually want

    %hash = (
       '4' => {
          '10' => [ 2, 5 ],
          '5'  => [ 2 ],
          '3'  => [ 2, 8 ],
        },
        '9' => {
           '4' => [ 3 ],
        },
    );
    

    Solution:

    my %hash;
    while (<>) {
       my @F = split;
       push @{ $hash{ $F[0] }{ $F[1] } }, $F[2];
    }
    

    Thanks to autovivification, that will automatically create the hashes and arrays as needed.

    You can always use join ',' afterwards if you really do want strings instead of arrays.

    for my $k1 (keys(%hash)) {
       for my $k2 (keys(${ $hash{$k1} })) {
          $hash{$k1}{$k2} = join(',', @{ $hash{$k1}{$k2} });
       }
    }