in reply to Re: Comma Delimited File
in thread Comma Delimited File
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"; }
"The first rule of Perl club is you don't talk about Perl club."
|
|---|