Even doing the extra work that wasn't asked for (sorting by "foo" the records where "bar" is equal), it isn't particularly hard. I'll sort "bar" descending and then "foo" ascending to illustrate the techniques a bit better:

my @list= <DATA>; @list= @list[ map { unpack "N", substr($_,-4) } sort map { # Only these two lines had to be written: my( $foo, $bar )= $list[$_] =~ / (\d+) /g; ~pack("N",$bar) . pack("N",$foo) . pack "N", $_ } 0..$#list ]; print @list; __END__ Item1 - 2 foo, 2 bar Item2 - 0 foo, 1 bar Item3 - 1 foo, 3 bar Item4 - 1 foo, 2 bar Item4 - 3 foo, 2 bar Item4 - 0 foo, 2 bar

Yes, this screams to be put into a module... (:

Rather than ~pack"N", you can also use ~sprintf"%09d" or even ~(length($n).$n)."\0" if you are dealing with non-negative integers, but pack"N" is nice in that it handles negative integers and rather large numbers and is fast.

- tye        


In reply to Re^2: Sort array according to a value in each element? (tye) by tye
in thread Sort array according to a value in each element? by McMahon

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.