[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] Processing a CSV file.



I have a simple CSV file with the header row, and a values row.  For a secondary system to process the data I need to massage the CSV into a Key-Value pair file.

Example of CSV:
name,age,gender,zip
john,33,male,68000

What I need is to produce a file with this:
name=john
age=33
gender=male
zip=68000

Using Text::CSV I'm close, but I don't like the code I came up with:
my $csv = Text::CSV->new( { binary => 1 } );
my $headers = $csv->parse($search_results_csv->getline());

my @headers2 = $csv->fields();
my $values = $csv->parse($search_results_csv->getline());
my @values2 = $csv->fields();
for (my $index = 0; $index < scalar @headers2; $index++ ) {
printf ("%s=%s\n", $headers2[$index], $values2[$index]);
}

Is there a cleaner way of getting the @headers2 and @values2 array and then walking through both of them in the for loop?

I thought I could set the header once (using column_names() ?) and then pull in the values line and do a foreach on the headers, but I couldn't get that to work.
 
Thoughts or examples?

Thanks,
Dan

--
***************** ************* *********** ******* ***** *** **
"Quis custodiet ipsos custodes?"
    (Who can watch the watchmen?)
    -- from the Satires of Juvenal
"I do not fear computers, I fear the lack of them."
    -- Isaac Asimov (Author)
** *** ***** ******* *********** ************* *****************