Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re: sorting a hash by keys, according to preference

by crashtest (Curate)
on Apr 13, 2005 at 04:54 UTC ( #447265=note: print w/replies, xml ) Need Help??

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 (Novice) 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!

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://447265]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2020-12-03 14:35 GMT
Find Nodes?
    Voting Booth?
    How often do you use taint mode?

    Results (56 votes). Check out past polls.