you might want to check out the CVS module if you have any quoted fields or the like, but if your data is as simple as your example then you could use something like this:
#!/usr/bin/perl use strict; my $col = $ARGV[1]; my $file = $ARGV[2]; $col--; my @data; open(IN,$file) || die "can't open: $!"; while(<IN>) { s/[\r\n]//g; push(@data,[ split(/,/,$_) ]); } close(IN); foreach (sort {$a->[$col] cmp $b->[$col]} @data) { print join(",",@{$_}),"\n"; }
I just coded this right off the top of my head, there may be errors. But you were looking for practice right? :)

Here's how this works. I take the column you want and the filename, decrement the column number (zero origin indexing), read in the file and make it a two dimensional array (or array or arrays, if you wish) then use sort (saying how to sort the elements) and print them back out.

I had slipped up and answered someone's homework once before, so I'm purposely being a little cryptic. That and I'm in a bit of a rush :). If you want a clearer explination, I'll come back and fill it later. But this should get you going in the right direction regardless.

/\/\averick

update:watch as Maverick makes silly typos! It's the CSV (comma seperated values) module not the CVS module which does something completely different altogether :)


In reply to Re: sorting comma separated value file by maverick
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.