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

Dear Perlmonks,

I would like to sort a hash combining two criteria:

- first by the hash key's string length
- and then by the hash key value, decreasing

Here is the sample data:

hard drive => 26
hard unit => 12
hard disk drive => 15
hard disk drive uni => 21
hard disk drive unit => 11

I'm using the following function to sort a hash by its value decreasingly:
sub hashValueDescendingNum { $count{$b} <=> $count{$a}; }
But I fail combining the two above mentioned criteria.

The output should look like

hard disk drive unit => 11
hard disk drive uni => 21
hard disk drive => 15
hard drive => 26
hard unit => 12

Thank you for your help.
Larry

Replies are listed 'Best First'.
Re: hash sorting
by ikegami (Patriarch) on Jan 25, 2009 at 17:07 UTC
    sub hashValueDescendingNum { length($b) <=> length($a) || $count{$b} <=> $count{$a} }

    On "ties", <=> returns zero, causing the RHS of the || to be evaluated.

      thank you very much