Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (8)
As of 2024-03-28 12:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found