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.... sort { $h{$b} <=> $h{$a} || $a cmp $b } keys %saved_key;
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.
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.)my @sorted = sort { $hash{$b} <=> $hash{$a} || $a cmp $b || func($a) <=> func($b) || $other{name}{$b} cmp $other{name}{$a} } @unsorted;
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 ]
In reply to Re: Re: Twice the pleasure of sorting a hash
by halley
in thread Twice the pleasure of sorting a hash
by coldfingertips
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |