I think I’m probably missing something obvious here, so please enlighten me.
Currently I’m reading a CSV file into perl using Text::CSV and it’s ‘parse’ method (outlined below).
csv->parse method:
while (<FILE>) {
if ($csv->parse($_)) {
my @columns = $csv->fields();
'refer to items with: $columns[1]'
}
else {
'Handle the parse error here'
}
}
I’m now looking for a way to read these values into a hash instead of an array. Going through the Text::CSV documentation it seems the most efficient way to do this is by using the ‘getline’ method (Outlined below), but I’m unsure how to catch errors in a similar manner to the way they are caught using the array approach.
csv->getline method:
my @cols = ("col1", "col2", "col3");
my $item = {};
$csv->bind_columns( \@{$item}{@cols} );
while( $csv->getline($it_fh) ) {
'refer to items using: $item->{col1}'
}
Any hints/tips/links would be great, as my Googleing seems to have come up empty?
EDIT: So here’s my understanding of the answer I’ve accepted, just to clarify what I understand as the fault tolerance of this method.
$csv->column_names( qw(col1 col2 col3) );
my $line;
until ( eof(FILE) ) {
$line++;
my $item = $csv->getline_hr( \*FILE );
if ( $item ) {
# refer to items as $item->{col1}
} else {
my $err = "Line: " . $line . "failed to parse\n"
. "Input: " . $csv->error_input . "\n"
. "Error: " . $csv->error_diag . "\n";
print STDERR $err;
}
}
Well, there’s always the straightforward approach:
However, I suspect that the following may be a bit more efficient, at least if using the XS implementation of Text::CSV: