Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: sorting a file - multilevel

by sgifford (Prior)
on Jun 14, 2008 at 02:15 UTC ( #692042=note: print w/replies, xml ) Need Help??


in reply to sorting a file - multilevel

As runrig mentioned, Unix sort(1) is a great tool for this, although the syntax sometimes requires a little trial and error.

To do this from Perl, read each line into some kind of data structure, then define your own sorting function that compares two of these data structures by looking at each of the fields, returning 1 if the first is greater, -1 if the second is greater, or going on to the next field if they are the same. The cmp and <=> ("spaceship") operators will help you with this, and they can be cascaded with the || "or" operator.

Here's a simple example (untested):

sub mysort { return $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] || $a->[9] cmp $b->[9] } my @list; while (<>) { chomp; push @list, [ split ]; } @list = sort mysort @list;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://692042]
help
Chatterbox?
[Corion]: Hi marto!
choroba greets
[choroba]: .org and .com not working for me today, only .net
Eily is connected on .org

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2017-10-23 09:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My fridge is mostly full of:

















    Results (277 votes). Check out past polls.

    Notices?