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

I have a hash which looks somewhat like the example posted below
AA01 => ALPHA = 453 OMEGA = 43 COUNT = 44 GF02 => ALPHA = 445 OMEGA = 4311 COUNT = 444 ...
So lets say in a text report I am printing it as follows
GROUP COUNT ALPHA OMEGA AA01 44 453 43 GF02 444 445 4311 .... ...
Now the user wants that they should be able to choose the way the report is sorted. If I use
sort keys { $a <=> $b} %hash
I can sort by the group name. Now what if I want to print the report sorted by COUNT, or ALPHA etc.,

Replies are listed 'Best First'.
Re: Some advice regaring sorting and hashes
by JavaFan (Canon) on Jun 08, 2009 at 11:53 UTC
    my $field = 'COUNT'; sort {$hash{$a}{$field} <=> $hash{$b}{$field}} keys %hash;
Re: Some advice regaring sorting and hashes
by targetsmart (Curate) on Jun 08, 2009 at 11:55 UTC
    you can use hash of arrays for that
    if your data is like this
    the inner array is [count, alpha, omega] respectively.
    $VAR1 = { 'a' => [ 0, 1, 2 ], 'b' => [ -1, 3, 4 ], 'c' => [ 4, 5, 6 ] };
    you can use something like below if you want to sort numerically by count
    sort { $hash{$a}[0] <=> $hash{$b}[0]} keys %hash

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
Re: Some advice regaring sorting and hashes
by markkawika (Monk) on Jun 08, 2009 at 23:51 UTC
    Your code:

    sort keys { $a <=> $b } %hash
    Is incorrect. Assuming the groups really look like "AA01" and "GF02", and assuming you want them in alphabetical order, and assuming these are in the hash %hash, this is what you want:
    sort { $a cmp $b } keys %hash