in reply to CSV Columns: Friend or foe?

Never start down the road leading to failure: parse CSV files with split.

Text::CSV_XS and Text::CSV already do your quest in an easy and reliable way:

$ cat test.pl #!/pro/bin/perl use strict; use warnings; use autodie; use Text::CSV_XS; my $csv = Text::CSV_XS->new ({ binary => 1 }); open my $fh, "<", "test.csv"; $csv->column_names ($csv->getline ($fh)); while (my $h = $csv->getline_hr ($fh)) { print "$h->{Name} => $h->{Cost}, $h->{Inventory}\n"; } $ cat test.csv Name,Cost,Inventory pickles,2.99,12 vegemite,4.00,8 nuclear sub,22.50,4 $ perl test.pl pickles => 2.99, 12 vegemite => 4.00, 8 nuclear sub => 22.50, 4 $

Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: CSV Columns: Friend or foe?
by Tux (Canon) on Dec 01, 2010 at 13:47 UTC

    And with a very small change, your sum's too:

    my %sum; $csv->column_names ($csv->getline ($fh)); while (my $h = $csv->getline_hr ($fh)) { print "$h->{Name} => $h->{Cost}, $h->{Inventory}\n"; no warnings "numeric"; $sum{$_} += $h->{$_} for $csv->column_names; } print <<EOS; Total Inventory: $sum{Inventory} Total Cost: $sum{Cost} EOS => pickles => 2.99, 12 vegemite => 4.00, 8 nuclear sub => 22.50, 4 Total Inventory: 24 Total Cost: 29.49

    Enjoy, Have FUN! H.Merijn