Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

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

by RMGir (Prior)
on Jul 06, 2007 at 12:40 UTC ( #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
Node Status?
node history
Node Type: note [id://625258]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2021-06-24 14:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)












    Results (128 votes). Check out past polls.

    Notices?