Search code examples
perlhashperl-data-structures

Regarding complex hashes in perl


I have a hash of hash, where my first key is name and second is some classes like level A, level B, level C and the values is d total number of students..

%hash{name}->{class}->number

So I fill my hash and everything is done but now when I print I get the number but if suppose a student name is in level A and level C and not in level B it should show

Name:level A = 1
     level B = 0
     level C = 1

How can I get my result like this? Please help me out..


Solution

  • use strict;
    use warnings;
    
    my %scores = (
        homer => { levA => 1, levC => 2 },
        bart =>  { levA => 3, levB => 4 },
    );
    
    my %all_levels = map { map {$_ => 1} keys %$_  } values %scores;
    
    for my $h (values %scores){
        for my $lev (keys %all_levels){
            $h->{$lev} = 0 unless exists $h->{$lev};
        }
    }