Your code has a pretty fundemental flaw where it assumes that all commas in the data are there to separate fields. CSV files allow commas to exist in quoted fields. That's why Text::CSV_XS (or even Text::ParseWords) are far better solutions.

But, if I knew that this wasn't going to be an issue, I'd do it something like this:

$_ = <DATA>; chomp; my @hdrs = split /,/; my @recs; while (<DATA>) { chomp; my %rec; @rec{@hdrs} = split /,/; push @recs, \%rec; }

That seems, to me, to create a far more useful data structure - an array of records, with each record being a reference to a hash where the keys are the header fields and the values are the associated data values.

Here's an example that then sorts the data on the second value in each record:

print "num1\tnum2\tnum3\n"; foreach (sort { $a->{num2} <=> $b->{num2} } @recs) { print "$_->{num1}\t$_->{num2}\t$_->{num3}\n"; }
--
<http://www.dave.org.uk>

"The first rule of Perl club is you don't talk about Perl club."


In reply to Re: Re: Comma Delimited File by davorg
in thread Comma Delimited File by curtisb

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.