Sunday, February 07, 2010

PERL: convert CSV file to hash

use Text::CSV;


open (my $CSV, "< file.csv") || die "Couldn't open file.csv";

my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();

# Assume first row contains column names.
$csv->column_names ($csv->getline ($DOMAINS));

while ( my $hr = $csv->getline_hr( $DOMAINS ) ) {
print $hr->{'Col1'} . "\n"; # 'Col1' is one of the column headers from first line of csv
}

No comments: