Search code examples
perlhashhash-of-hashes

Get value from hash of hashes


I would like to get value from hash of hashes but i do not. My code is :

sub test {
    my $filename = $_[0];
    open INFILE, ${filename} or die $!;
    my %hashCount;
    my @firstline = split('\t',<INFILE>);
    shift(@firstline);
    while (my $line = <INFILE>) 
    {
        my %temp;
        chomp($line);
        my @line = split('\t', $line);
        foreach my $cpt (1..$#line) {
            $temp{$firstline[$cpt-1]}=$line[$cpt];
        }
        $hashCount{$line[0]}={%temp};
    }
    return %hashCount;
}
sub get_hash_of_hash { 
    my $h = shift; 
    foreach my $key (keys %$h) { 
        if( ref $h->{$key}) { 
            get_hash_of_hash( $h->{$key} );
        } 
        else { 
            say $h->{$key};
        } 
    } 
}

And when i display my hash :

$VAR10679 = 'M00967_43_1106_2493_14707';
$VAR10680 = {
          'A' => '1',
          'B' => '0',
          'C' => '1',
          'D' => '0',
          'E' => '0'
        };

My first function return my hash of hashes and i get my specific value with the second function. So I want to get value like that :

my %hashTest = test("FILE.txt"); get_hash_of_hash(%hashTest,"M00967_43_1106_2493_14707","A") //return value '1'


Solution

  • You can either access nested elements like

    $hash{keyA}{keyB}
    

    or we can write a function that walks the data structure, like

    sub walk {
      my ($hashref, @keys) = @_;
      my $pointer = $hashref;
      for my $key (@keys) {
        if (exists $pointer->{$key}) {
          $pointer = $pointer->{$key};
        } else {
          die "No value at ", join "->", @keys;
        }
      }
      return $pointer;
    }
    

    which can be used like

    my %hash = (
      'M00967_43_1106_2493_14707' => {
          'A' => '1',
          'B' => '0',
          'C' => '1',
          'D' => '0',
          'E' => '0'
      },
    );
    say walk(\%hash, 'M00967_43_1106_2493_14707', 'A');
    

    Note: When using Data::Dumper, pass references to the Dump function:

    print Dump \%hash; # not print Dump %hash
    

    This is neccessary to show the correct data structure.