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

Re: Sorting rows in a text file

by thinker (Parson)
on Nov 09, 2001 at 19:18 UTC ( [id://124380]=note: print w/replies, xml ) Need Help??


in reply to Sorting rows in a text file

Hi saihuj,

This code is by no means robust, but it should work if the data files are in _exactly_ the form you state.

Also, I am not sure whether 15/19/2001 means the 15th day of the 19th month, or vice versa. Whatever, that month is out of scale in my planet :-). So I assume dd/mm/yy

Oh, and it doesn't check the integrity of dates :-). Did I mention that.

Still, I hope the sort code can help you become familiar with how things work.

#!/usr/bin/perl -w use strict; open DATA, "./data.txt"; # or wherever the file is my @data=<DATA>; my @sorted = sort sort_func @data ; for(@sorted){print $_}; sub sort_func{ my ($a_dd,$a_mm,$a_yy)=$a =~ m|(\d*)/(\d*)/(\d*)|; my ($b_dd,$b_mm,$b_yy)=$b =~ m|(\d*)/(\d*)/(\d*)|; return ( $a_yy<=>$b_yy || $a_mm<=>$b_mm || $a_dd<=>$b_dd); }
cheers

thinker

Replies are listed 'Best First'.
Re: Re: Sorting rows in a text file
by maverick (Curate) on Nov 09, 2001 at 20:18 UTC
    thinker's solution is perfectly valid. However it's probably not the most efficient way to do it. This may be a concern if you have a lot of data.

    So, I'll suggest using a Schwartzian Transform (an algorithm created by our very own merlyn).

    untested code:

    #!/usr/bin/perl -w use strict; open (DATA, "./data.txt") or die $!; # for example my @sorted = map { $_->[1] } sort { $a->[0] cmp $b->[0] } map { [ &fix_date($_), $_ ] } <DATA>; for (@sorted) { print $_ }; sub fix_date { my ($d,$m,$y) = ( shift =~ m|(\d\d)/(\d\d)/(\d{4})| ); return "$y-$m-$d"; }
    The basic speed eater for thinker's way is that you have to munge the date to sort it a great number of times.

    The first (lower) map does the time expensive data munging, into a form that's easy for sort to deal with, and the last (top) map puts the data back into the original form

    HTH

    /\/\averick
    perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (5)
As of 2024-04-19 22:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found