http://www.perlmonks.org?node_id=348123


in reply to Twice the pleasure of sorting a hash

Use following code for sorting

sort {$tmp = $saved_key{$b} <=> $saved_key{$a}; $tmp = $a cmp $b if ($tmp == 0); $tmp} keys %saved_key

Temporary variable is not needed of course

Replies are listed 'Best First'.
Re: Re: Twice the pleasure of sorting a hash
by halley (Prior) on Apr 26, 2004 at 13:52 UTC
    While your code works, it's one of those occasions where you're making code less readable by being more explicit.
    ... sort { $h{$b} <=> $h{$a} || $a cmp $b } keys %saved_key;
    Unlike C or Java, the Perl operator || keeps the actual true value. (C or Java would just return 1; but they don't have <=> either.) This means (among other things) that Perl can cascade a number of possible criteria in a single statement. By avoiding the visual clutter of temporary variables and unnecessary checks against zero, your code can be more readable.

    This is the Perl idiom. List each criteria from most important to least important. The first criteria which returns a -1 or 1 will decide the sort order; any criteria returning 0 will fall through to the next part of the expression.

    my @sorted = sort { $hash{$b} <=> $hash{$a} || $a cmp $b || func($a) <=> func($b) || $other{name}{$b} cmp $other{name}{$a} } @unsorted;
    I find that a newline after each criteria helps the reader immediately understand what's going on. (The extra spacing on each line is optional.)

    This newline on each phase technique is useful of any of the Perl-style "list pipelines" which are common, such as those with colorful names like the Schwartzian Transform or the Orcish Maneuver.

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