http://qs1969.pair.com?node_id=812014


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.