Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: hash from CSV-like structure

by naChoZ (Curate)
on Jan 05, 2008 at 00:31 UTC ( #660490=note: print w/ replies, xml ) Need Help??


in reply to hash from CSV-like structure

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.


Comment on Re: hash from CSV-like structure
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://660490]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (11)
As of 2014-09-01 08:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (299 votes), past polls