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

How do I sort on more than one column?

by Russ (Deacon)
on Jul 23, 2000 at 23:51 UTC ( [id://24003]=perlquestion: print w/replies, xml ) Need Help??

Russ has asked for the wisdom of the Perl Monks concerning the following question: (sorting)

How do I sort on more than one column?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I sort on more than one column?
by Russ (Deacon) on Jul 23, 2000 at 23:52 UTC
    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.

    Russ

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://24003]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-03-19 07:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found