user2886545
user2886545

Reputation: 713

hash of hashes in Perl, get keys

I have the following code:

$num = keys %{$hash_o_count{$genename}{$allname}};
print $num."\n";
$hash_o_count{$genename}{$allname} = $num + 1;

I'd like to have the number of keys I have in a nested hash, but I don't know how to get it even though an extensive research on Google.

Any help? Thanks.

Upvotes: 1

Views: 334

Answers (2)

Chankey Pathak
Chankey Pathak

Reputation: 21676

#!/usr/bin/perl
use strict;
use warnings;
my %HoH = (
    flintstones => {
        husband   => "fred",
        pal       => "barney",
    },
    jetsons => {
        husband   => "george",
        wife      => "jane",
        "his boy" => "elroy",  # Key quotes needed.
    },
    simpsons => {
        husband   => "homer",
        wife      => "marge",
        kid       => "bart",
    },
);
my $cnt=0;
for my $family ( keys %HoH ) {
    $cnt++;
    for my $role ( keys %{ $HoH{$family} } ) {
         $cnt++;
    }
}
print "$cnt"; #Output is 11

A bit modified version of code from Programming Perl.

Demo

Upvotes: 0

Neil H Watson
Neil H Watson

Reputation: 1070

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

my %hash;
$hash{level1}{level2}{level3} =
{
   one => 'apple',
   two => 'orange'
};

my $bottom_level_keys = keys %{ $hash{level1}{level2}{level3} };
say $bottom_level_keys. " keys at the bottom level"; 

Upvotes: 1

Related Questions