in reply to Re^5: problems parsing CSV
in thread problems parsing CSV

Ok, here's the same script using bind_columns.

#!/usr/bin/perl use strict; use warnings; use English qw( -no_match_vars ); use Text::CSV; $OUTPUT_FIELD_SEPARATOR = "\n"; $OUTPUT_RECORD_SEPARATOR = "\n"; my $release_file = '../ecodata/releases.txt'; open my $release_fh, '<', $release_file or die "Can't open release file $release_file: $OS_ERROR\n"; my $csv = Text::CSV->new({ auto_diag => 1, binary => 1, allow_loose_quotes => 1, escape_char => '\\', }); my %value; # Header is 'TRI,Release#,ChemName,RegNum,Year,Pounds,Grams' my @column_labels = $csv->column_names($csv->getline($release_fh)); $csv->bind_columns(\@value{@column_labels}); while ($csv->getline_hr($release_fh)) { { no warnings 'numeric'; if ($value{'Pounds'} == 0.0 and $value{'Grams'} == 0.0) { warn "Release $value{'Release#'} is weightless\n"; } } print $value{'TRI'}, $value{'Release#'}, $value{'ChemName'}, $value{'RegNum'}, $value{'Year'}, $value{'Pounds'}, $value{'Grams'}; } close $release_fh; exit 0;

I had to change your...

\@value{@{$csv->column_names($csv->getline($release_fh))}}
...to...
\@value{$csv->column_names($csv->getline($release_fh))}

Replies are listed 'Best First'.
Re^7: problems parsing CSV
by Tux (Canon) on Oct 13, 2010 at 06:20 UTC

    You are now mixing two approaches. When using bind_columns () you should not use getline_hr () but getline (), because you are not returning a hashref but reading into prebound variables:

    my @column_labels = @{$csv->getline ($release_fh)}; $csv->bind_columns (\@value{@column_labels}); while ($csv->getline ($release_fh)) { : }

    You do not use the method column_names () at all. That was a cut-n-paste error from your code in my previous example. Mea culpa.

    \@value{@{$csv->column_names ($csv->getline ($release_fh))}} => \@value{@{$csv->getline ($release_fh)}};

    Enjoy, Have FUN! H.Merijn

      I thought it seemed awfully busy. This is much more understandable:

      #!/usr/bin/perl use strict; use warnings; use English qw( -no_match_vars ); use Text::CSV; $OUTPUT_FIELD_SEPARATOR = "\n"; $OUTPUT_RECORD_SEPARATOR = "\n"; my $release_file = '../ecodata/releases.txt'; open my $release_fh, '<', $release_file or die "Can't open release file $release_file: $OS_ERROR\n"; my $csv = Text::CSV->new({ auto_diag => 1, binary => 1, allow_loose_quotes => 1, escape_char => '\\', }); my %value; # Header is 'TRI,Release#,ChemName,RegNum,Year,Pounds,Grams' $csv->bind_columns(\@value{@{$csv->getline($release_fh)}}); while ($csv->getline($release_fh)) { { no warnings 'numeric'; if ($value{'Pounds'} == 0.0 and $value{'Grams'} == 0.0) { warn "Release number $value{'Release#'} is weightless\n"; } } print $value{'TRI'}, $value{'Release#'}, $value{'ChemName'}, $value{'RegNum'}, $value{'Year'}, $value{'Pounds'}, $value{'Grams'}; } close $release_fh; exit 0;

      Thank you, Tux.