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开发者_StackOverflow中文版 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..
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};
}
}
This is a bit of a stretch, but what I think you're after is to assign a value of zero to all (name,class) pairs for which $hash{name}->{class}
is undefined. So, given that...
my @classes; #First, we grab all of the possible classes.
foreach my $name (sort keys %hash)
{
foreach my $class (sort keys %{$hash->{$name}})
{
push @classes, $class unless $class~~@classes;
}
}
@classes=sort @classes #or sort{$a<=>$b}@classes, depending on the datatype...
foreach my $name(sort keys %hash)
{
foreach my $class(@classes)
{
$hash->{$name}->{$class}=0 unless defined $hash->{$name}->{$class};
}
}
精彩评论