In this case, I can see one immediate problem which Sort::Field isn't going to help you with: dealing with the string v. numeric form of the data. I don't have a good answer to that problem, either.
For something like this, the first-draft of my version of this wheel would look something like so, assuming string-comparison was sufficient:
The first loop reads in the CSV records, crudely splits them on commas, stores the results in an anonymous array, which it adds to the @records array. This is not robust -- it'll fail when the fields of the record contain quoted commas -- but for a first cut, it'll do the job.# $n contains field to sort on # records to sort are in @ARGV my @records; while (<>) { # chomp deleted so we don't have to add \n later push @records, [ split ',' ]; } # now sort them; @records = sort { $$a[$n] cmp $$b[$n] } @records; # now print them foreach $record (@records) { print join (',',@$record); }
The sort line sorts the @records array using the code block given as the comparison function. In this case, since we know that each element of @records is a reference to an array, with each sub-array element being one of the original fields, we can access the nth field with $$a[$n], so the comparison function simply compares the nth field of the two records.
Finally, we output the now-sorted array.
In reply to RE: sorting comma separated value file
by BlaisePascal
in thread sorting comma separated value file
by taopunk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |