in reply to sorting a hash by keys, according to preference

For general reference, if you do need to sort strings in a predetermined, non-alphabetical order, I believe the following is a common form:
sub by_pref { ($b eq 'start') <=> ($a eq 'start') or ($b eq 'stop') <=> ($a eq 'stop') or ($b eq 'step') <=> ($a eq 'step') }
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.

Replies are listed 'Best First'.
Re^2: sorting a hash by keys, according to preference
by vindaloo (Acolyte) on Apr 14, 2005 at 01:09 UTC

    It turns out I was after two things in my question: How to sort the hash the way I wanted and how to sort the hash using a common hand-crafted sort function with the space-ship operator. I am glad to see these working examples for both for my future sorting needs. I may just play around with this sort function to get a handle on how it works.

    Thanks again!