Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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

by mmittiga17 (Scribe)
on Dec 09, 2009 at 19:39 UTC ( #812014=note: print w/replies, xml ) Need Help??


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

here is some code I borrowed that would work. if I can figure out how to get rid of preceeding "00" in a column:

#!/usr/bin/perl my $sheet; my $count = -1; while( <DATA> ) { chomp; $count++; # skip header next unless $count; my $row; @$row = split( /,/, $_ ); push @$sheet, $row; } foreach my $row ( sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } +@$sheet ) { print join( ',', @$row ), "\n"; } __DATA__ Name,Score,State "001","67","CA" "2","67","CA" "12","63","FL" "1","72","IL" "1","32","AZ"

Replies are listed 'Best First'.
Re^2: How do I sort a CSV file on multiple columns?
by AnomalousMonk (Archbishop) on Dec 09, 2009 at 20:18 UTC

    The  <=> numeric comparison automatically numerifys to a decimal number before the comparison:

    >perl -wMstrict -le "my @l = qw(10 010 0010 8 08 008 9 09 009 1 01 001); @l = sort { $a <=> $b } @l; print qq{@l}; " 1 01 001 8 08 008 9 09 009 10 010 0010
Re^2: How do I sort a CSV file on multiple columns?
by kennethk (Abbot) on Dec 09, 2009 at 20:29 UTC
    The issue with your posted code can be traced back to your not using Text::CSV to parse the data, which I find ironic given your node title (Update: previous title "Text::CSV"). With your splitting above, your data values are $x = '"001"', not the $x = '001' you seem to expect. If you had turned on warnings, you would have gotten Argument ""2"" isn't numeric in numeric comparison (<=>) repeatedly, since "2" is clearly not numeric. Text::CSV will automatically clean up the quotes, and thus your numbers would have been properly be interpreted as numbers. A la:
    #!/usr/bin/perl use strict; use warnings; use Text::CSV; my $sheet; my $count = -1; my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attr +ibute. or die "Cannot use CSV: ".Text::CSV->error_diag (); my @rows = (); while ( my $row = $csv->getline( *DATA ) ) { push @rows, $row; } my $header = shift @rows; foreach my $row ( sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } +@rows ) { print join( ',', @$row ), "\n"; } __DATA__ Name,Score,State "001","67","CA" "2","67","CA" "12","63","FL" "1","72","IL" "1","32","AZ"

    See Use strict warnings and diagnostics or die.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (9)
As of 2023-02-01 14:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (10 votes). Check out past polls.

    Notices?