Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

How do I sort on more than one column?

by Russ (Deacon)
on Jul 23, 2000 at 23:51 UTC ( #24003=categorized question: print w/replies, xml ) Need Help??
Contributed by Russ on Jul 23, 2000 at 23:51 UTC
Q&A  > sorting

Answer: How do I sort on more than one column?
contributed by Russ

The comparison operators return 0 when the operands are equal. So, using the || operator, we can sort first by one column, then another (as many as we want).

@data = ( [qw(Bubba brutalski 20)], [qw(Bubba brutalski 10)], [qw(JoeBob brutalski 20)], [qw(Jethro brutalski 20)], [qw(Junior brutalski 20)], ); # Sorted by Name (Last, First) @ByName = sort {$a->[1] cmp $b->[1] || $a->[0] cmp $b->[0]} @data; # Sorted by Name, then score @FullSort = sort {$a->[1] cmp $b->[1] || $a->[0] cmp $b->[0] || $a->[2] <=> $b->[2]} @data;
In the second example above, @FullSort looks like:
( [Bubba, brutalski, 10], [Bubba, brutalski, 20], [Jethro, brutalski, 20], [JoeBob, brutalski, 20], [Junior, brutalski, 20] )
because it is sorted by Last Name, then First Name, then Score.


Please (register and) log in if you wish to add an answer

  • 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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    [Happy-the-monk]: Moin !

    How do I use this? | Other CB clients
    Other Users?
    Others lurking in the Monastery: (4)
    As of 2018-07-23 08:10 GMT
    Find Nodes?
      Voting Booth?
      It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

      Results (459 votes). Check out past polls.