It's fairly readable (as in the sort order is visibile at a glance)... and more importantly it's fun to figure out how it works. At least it was for me the first time I came across this idiom, and it's a rare opportunity to use the spaceship operator (check perlop if you haven't seen it before). Briefly, each of the three branches of the or expression only evaluate to true if exactly one of $a or $b is equal to the string being checked in that line. For instance, ($b eq 'start') <=> ($a eq 'start') evaluates to (1) <=> (1) #(== 0) if both $a and $b equal "start", and to (0) <=> (0) #(== 0) if both aren't. So then the next part of the or chain is checked. If exactly one of $a or $b is equal to "start" however, the appropriate comparison is returned. If $a eq $b, the entire expression returns 0, as it's supposed to. It's easier to see how it works if you step through it with specific examples. In this case, hardcoding the order as Tanktalus and dave0 suggest makes more sense. That way, you avoid sorting altogether.sub by_pref { ($b eq 'start') <=> ($a eq 'start') or ($b eq 'stop') <=> ($a eq 'stop') or ($b eq 'step') <=> ($a eq 'step') }
In reply to Re: sorting a hash by keys, according to preference
by crashtest
in thread sorting a hash by keys, according to preference
by vindaloo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |