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

Hi, I don't want to spam the chatterbox anymore, but I am still stuck on how to sort a nested hash within a hash of hashes.

# here's my test hash my %hash; $hash{"Rock Bands"}{"Smashing Pumpkins"} = "5 stars"; $hash{"Rock Bands"}{"Aerosmith"} = "5 stars"; $hash{"Rock Bands"}{"Foo Fighters"} = "5 stars"; $hash{"Pop Bands"}{"Duran Duran"} = "5 stars"; $hash{"Pop Bands"}{"Blondie"} = "5 stars"; foreach my $key (sort keys %hash) { # this bit sorts ok print "KEY: $key \n"; while (my ($nestedKey, $value) = each %{ $hash{$key} } ) { # but I can't work out how to sort this iteration print "nested key: $nestedKey \n"; } print "-------\n"; }

This returns:

KEY: Pop Bands
nested key: Duran Duran
nested key: Blondie
-------
KEY: Rock Bands
nested key: Foo Fighters
nested key: Smashing Pumpkins
nested key: Aerosmith
-------

But I would like it to return:

KEY: Pop Bands
nested key: Blondie
nested key: Duran Duran
-------
KEY: Rock Bands
nested key: Aerosmith
nested key: Foo Fighters
nested key: Smashing Pumpkins
-------

Any suggestions would be welcome, thanks!!

Replies are listed 'Best First'.
Re: Sorting hash of hashes
by Zaxo (Archbishop) on Jun 21, 2007 at 19:25 UTC

    Replace the while each loop with,

    for (sort keys %{$hash{$key}}) { print "nested key: $_ \n"; }
    Hashes don't stay sorted.

    After Compline,
    Zaxo

      for my $nestedKey (sort keys %{$hash{$key}})

      Surely?

      update: bah! Stealth edit:(

Re: Sorting hash of hashes
by Util (Priest) on Jun 21, 2007 at 19:31 UTC

    You can't use each(%foo) to process a hash in sorted order.

    my %type_bands_rating_HoH = ( "Rock Bands" => { "Smashing Pumpkins" => "5 stars", "Aerosmith" => "5 stars", "Foo Fighters" => "5 stars", }, "Pop Bands" => { "Duran Duran" => "5 stars", "Blondie" => "5 stars", }, ); foreach my $type ( sort keys %type_bands_rating_HoH ) { my $band_rating_href = $type_bands_rating_HoH{$type}; print "KEY: $type \n"; foreach my $band ( sort keys %{ $band_rating_href } ) { my $rating = $band_rating_href->{$band}; print "nested key: $band, rating $rating\n"; } print "-------\n"; }

Re: Sorting hash of hashes
by FunkyMonk (Bishop) on Jun 21, 2007 at 19:27 UTC
    foreach my $key (sort keys %hash) { print "KEY: $key \n"; for my $nested_key ( sort keys %{ $hash{$key} } ) { print "nested key: $nested_key \n"; } print "-------\n"; }

    I think that (re-)reading perldsc would help your perl progress.

    update: Who put that there? Superfluous line removed!

Re: Sorting hash of hashes
by Herkum (Parson) on Jun 21, 2007 at 19:27 UTC

    I think that should work for you.

    for my $key (sort keys %hash) { print "KEY: $key \n"; for my $subkey (sort keys %{$hash{$key}} ) { print "nested key: $subkey => $hash{$key}{$subkey} \n"; } print "-------\n"; }