dekul has asked for the wisdom of the Perl Monks concerning the following question:
I am parsing a CSV file and I would like to turn the columns into individual arrays contained in a hash which I can access by name (names are contained in the header line of the input file).
Example input file (MyCSV.csv):
Name,Cost,Inventory pickles,2.99,12 vegemite,4.00,8 nuclear sub,22.50,4
What I have done thus far:
open IN, "MyCSV.csv" or die "Cannot open input file: $!\n"; my ($line, @colNames, $size, %columns, $j); $j = 0; chomp($line =<IN>); # Read the column header @colNames = split(',',$line); $size = scalar @colNames; while($line = <IN>) { chomp($line); push @{$columns{$colNames[$j++ % $size]}}, $_ for(split(',', $line +)); } # Now I can play with whole columns of data by name print “Total Inventory = ”, List::Util::sum(@{$columns{'Inventory'}}), + “\n”; print “Total Cost = ” , List::Util::sum(@{$columns{'Cost'}}), “\n”;
A couple of quick notes:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: CSV Columns: Friend or foe?
by MidLifeXis (Monsignor) on Jul 27, 2010 at 13:43 UTC | |
|
Re: CSV Columns: Friend or foe?
by Anonymous Monk on Jul 27, 2010 at 02:14 UTC | |
by Anonymous Monk on Dec 01, 2010 at 13:19 UTC | |
|
Re: CSV Columns: Friend or foe?
by Gangabass (Vicar) on Jul 27, 2010 at 04:58 UTC | |
|
Re: CSV Columns: Friend or foe?
by suhailck (Friar) on Jul 27, 2010 at 03:42 UTC | |
|
Re: CSV Columns: Friend or foe?
by doug (Pilgrim) on Jul 28, 2010 at 02:23 UTC | |
|
Re: CSV Columns: Friend or foe?
by Tux (Canon) on Dec 01, 2010 at 13:38 UTC | |
by Tux (Canon) on Dec 01, 2010 at 13:47 UTC | |
|
Re: CSV Columns: Friend or foe?
by JavaFan (Canon) on Dec 01, 2010 at 13:58 UTC |