While merlyn has suggested the best answer (don't re-invent the wheel), that doesn't help you if your reason for doing this is to learn how the wheel was made to begin with.

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:

# $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 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.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.