momo33 has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I have a hash of hashes, and want to iterate over a "subhash". What I made does not work.

I have a hash of hashes %pupils: $pupils{$class}->{$name}=$score
(the real program is very different, but the structure is essentially the same)

Now I want to iterate over the pupil-names in one class:
foreach my $nm ( keys $pupils{$class}) {
push( @namelist, $nm )
}

This does not work. How can I get it right?

Thank you,
Mo

Replies are listed 'Best First'.
Re: foreach and hash of hashes
by jwkrahn (Abbot) on Jun 12, 2009 at 17:06 UTC

    Change  keys $pupils{$class} to  keys %{$pupils{$class}}

    Or you could do it like this:

    push @namelist, keys %{$pupils{$class}};
Re: foreach and hash of hashes
by ~~David~~ (Hermit) on Jun 12, 2009 at 16:59 UTC
    It seems like you might be mixing up ways of de-referencing the hash of hashes.
    my $pupils = \%pupils; foreach my $nm ( keys %{$pupils->{$class}} ){ push @namelist, $nm; }
      Thank you all for the reactions. I think I'm starting to understand it.
Re: foreach and hash of hashes
by Transient (Hermit) on Jun 12, 2009 at 17:09 UTC
    #!/usr/bin/perl use strict; use warnings; my %pupils = ( 'Foo 101' => { 'Bob' => 88, 'Sally' => 99 }, 'Foo 102' => { 'Jesse' => 68, 'Raphael' => 93 } ); my $class_to_check = "Foo 102"; my @namelist; foreach my $nm ( keys %{$pupils{$class_to_check}} ) { push @namelist, $nm; } print "Student in $class_to_check: $_\n" foreach @namelist;
    Basically you're missing a '%' in keys $pupils{$class} <sic>