Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Read the csv file to a hash....

by RMGir (Prior)
on Jul 06, 2007 at 12:40 UTC ( [id://625258]=note: print w/replies, xml ) Need Help??


in reply to Read the csv file to a hash....

Hmm, this sounds like fun homework. :)

My solution doesn't deal with "ragged" .csv's -- if there's a line with more entries than the others, things will get thrown off. That's easy to fix, I'll leave that to you.

use strict; use warnings; use Data::Dumper qw(Dumper); open(INPUT,"foo.csv") or die "Can't open foo.csv, $!"; my @columns; my %hash; while(<INPUT>) { chomp; my $index=0; if(/"/) { push @{$columns[$index++]},$2 while /("+)(.*?)\1/g; } else { push @{$columns[$index++]},$1 while /([^,]+)/g; } } my @headings=map {shift @$_} @columns; print "Headings: @headings\n"; @hash{@headings}=@columns; print "Hash contents:\n"; print Dumper(\%hash);

Mike

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2024-03-28 17:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found