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

I have a hash of arrays of the following structure...
%HoA = ( part1 => [ 'Sc', 'John', 'Jacob', 'Jingle' ], part2 => [ 'Sc', 'Diffie', 'Whitman' ] jpart3 => [ 'Mo', 'Diffie', 'Duffy' ] );
I am able to sort by keys using...
sub sort_keys_ascending{ sort keys %HoA }
and I am able to sort by value using...
my $href = \%HoA; sub sort_typeparm_ascending{ sort{ $href->{$a}[$col_id] cmp $href->{$b}[$col_id] } keys %data }
The problem arises when I want to sort by value, then by the key itself...
sub sort_typeparm_descending{ sort{ $href->{$b}[ 0 ] cmp $href->{$a}[ 0 ] || ????? KEY{$b} ????? cmp ????? KEY{$a} ????? } keys %data; }
Do you fellas know if it's possible to do it in this format or am I completely on the wrong path? I can't find any info on how to do this. Thanks in advance, Deke

Replies are listed 'Best First'.
Re: How do I sort a hash of arrays by value THEN by key?
by halley (Prior) on Aug 29, 2005 at 16:17 UTC
    You were very close. I adjusted indentation a little.
    sort { $href->{$b}[ 1 ] cmp $href->{$a}[ 1 ] || $b cmp $a } keys %data;
    You can chain any number of conditions with the || operator. The special globals $a and $b get the keys (e.g., 'part2') to compare.

    --
    [ e d @ h a l l e y . c c ]

Re: How do I sort a hash of arrays by value THEN by key?
by salva (Canon) on Aug 29, 2005 at 16:56 UTC
    Do you fellas know if it's possible to do it in this format or am I completely on the wrong path?

    you are on the right path, but as usual TMTOWTDI...

    # ascending use Sort::Key::Maker sort_ss => qw(str str); my @akeys = sort_ss { $data{$_}[0], $_ } keys %data; # descending use Sort::Key::Maker sort_rsrs => qw(-str -str); my @dkeys = sort_rsrs { $data{$_}[0], $_ } keys %data;