简体   繁体   中英

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.

#!/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"; 
#!/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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM