Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: How do I sort a CSV file on multiple columns?

by GrandFather (Saint)
on Dec 09, 2009 at 22:30 UTC ( [id://812057]=note: print w/replies, xml ) Need Help??


in reply to How do I sort a CSV file on multiple columns?

Following up on the DBD::CSV suggestions by others this may get you started:

use strict; use warnings; use DBI; my $tmpFileName = 'temp'; open my $outFile, '>', $tmpFileName or die "Can't open $tmpFileName: $ +!\n"; print $outFile $_ for <DATA>; close $outFile; my $dbh = DBI->connect ("DBI:CSV:") or die "DBI connect failed: $DBI::errstr"; my $sth = $dbh->prepare ("SELECT * FROM temp ORDER BY Name, Score"); $sth->execute(); while (my $row = $sth->fetchrow_hashref) { print "@{$row}{'Name', 'Score', 'State'}\n"; } $sth->finish(); $dbh->disconnect(); __DATA__ Name,Score,State "001","67","CA" "2","67","CA" "12","63","FL" "1","72","IL" "1","32","AZ"

Prints:

1 32 AZ 001 67 CA 1 72 IL 2 67 CA 12 63 FL

True laziness is hard work

Replies are listed 'Best First'.
Re^2: How do I sort a CSV file on multiple columns?
by Tux (Canon) on Dec 10, 2009 at 16:33 UTC

    I'd like to note (and obviously promote) the use of new syntax in DBD::CSV available now:

    my $dbh = DBI->connect ("dbi:CSV:", undef, undef, { PrintError => 1, RaiseError => 1, f_dir => ".", f_ext => ".csv/r", f_schema => undef, csv_null => 1, csv_auto_diag => 1, });

    Using f_ext like that enables you to mix code (.pl-files) and data (.csv-files) in a single directory, and still be able to only see the tables (without the .csv extension).

    merijn@tux:~> cat xx.pl #!/pro/bin/perl use strict; use warnings; use DBI; my $dbh = DBI->connect ("dbi:CSV:", undef, undef, { RaiseError => 1, PrintError => 1, f_dir => ".", f_ext => ".csv/r", f_schema => undef, csv_null => 1, csv_auto_diag => 1, }); my $sth = $dbh->prepare ("select b, e from xx order by d, f"); $sth->execute; while (my @row = $sth->fetchrow_array) { print "@row\n"; } merijn@tux:~> cat xx.csv a,b,c,d,e,f 1,2,3,4,5,6 1,3,4,5,3,4 2,5,2,5,2,5 2,4,1,5,8,1 3,5,2,8,1,9 4,5,6,7,8,9 5,1,4,2,5,3 6,2,5,7,1,8 merijn@tux:~> ls -d x* x0 x1 xloadall xx xx.csv xx.pl merijn@tux:~> perl xx.pl 2 5 3 3 5 2 4 8 5 1 5 8 1 5 2 1 merijn@tux:~>

    Enjoy, Have FUN! H.Merijn

Log In?
Username:
Password:

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

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

    No recent polls found