I wrote a subroutine to do almost the exact same thing just recently (though I ended up converting it to import to a db). Here it is with my db related stuff commented and fixed to populate a hashref like you've described with some sample usage based on your example.
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Parse::CSV;
my @list_of_fields = qw/
field1
field2
field3
field4
field5
field6
/;
my $values = import_csv({ filename => '/tmp/vals.csv',
fields => \@list_of_fields });
print "CSV Import complete...\n";
print Dumper( $values );
# {{{ import_csv
#
sub import_csv {
my $args = shift;
# die "No database handle provided for import...\n" unless defined
+$args->{dbh};
# die "No database table provided for import...\n" unless defined
+$args->{table};
die "No database columns provided for import...\n" unless defined
+$args->{fields};
# my $dbh = $args->{dbh};
my $table = ref $args->{table} eq 'ARRAY'
? $args->{table}->[0]
: $args->{table} ;
my $fields = $args->{fields}
? $args->{fields}
: 'auto';
my $csv = Parse::CSV->new( file => $args->{filename},
fields => $fields,
sep_char => '|',
);
my $results = {};
while ( my $row = $csv->fetch ) {
my @columns = @{ $fields };
# Make certain that the number of values returned is
# equal to the number of columns we're expecting.
#
die "Invalid number of columns...\n" unless scalar @columns ==
+ scalar keys %{ $row };
# Creating placeholders this way so we'll always
# have the exact right number of placeholders to
# match the number of values in the columns list for
# our sql statement.
#
# my @placeholders = map { '?' } @$columns;
# my @values = map { $row->{$_} } sort @columns;
# my $results = insert_row({ dbh => $dbh,
# columns => \@columns,
# table => $table,
# 'values' => \@values,
# });
$results->{ $row->{field1} }->{ $row->{field3} } = $row->{fiel
+d5};
}
return $results;
} # }}}
Output:
# perl /tmp/test-parsing.pl
CSV Import complete...
$VAR1 = {
'200326951' => {
'rel_Access2' => '200315786',
'rel_Access1' => '200315786'
}
};
--
naChoZ
Therapy is expensive. Popping bubble wrap is cheap. You choose.