in reply to Re: Read the csv file to a hash....
in thread Read the csv file to a hash....

<$fh>;  # Drop column names on the floor
Somehow, it hurts me to see this in void context :-)
#!/usr/bin/perl use strict; use warnings; use Text::ParseWords; # WARNING: this code may generate some warnings # but checking is omitted intentionally my @headers; { local $_ = <DATA>; chomp; @headers = parse_line(',', 0, $_); } my @people; while (<DATA>) { chomp; my @fields = parse_line(',', 0, $_); push @people, { map { $headers[$_], $fields[$_] } 0 .. $#headers } +; } printf qq(%s says "%s"\n), @{$people[0]}{@headers}; # Isha says "Hello!!" __DATA__ Name,Comment "Isha","""Hello!!""" "Malav" ,"""koni comments nakhu ? tari?""" "Mihir","""Dont know what to write :)""" "Mukesh","""Kya comment add karun""" "Tanmay Anjaria","""I - Intelligent S - Smart H - Highly thoughtful A +- Antonyms should be taken for all of the above to know Isha :-)) Jus +t Kidding... Keep Smiling, dear\u2026"""
Or, following original requirement exactly:
my %people; while (<DATA>) { chomp; my @fields = parse_line(',', 0, $_); for (0 .. $#headers) { push @{$people{$headers[$_]}}, $fields[$_]; } } printf qq(%s says "%s"\n), map { $people{$_}[0] } @headers; # Isha says "Hello!!"

Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Replies are listed 'Best First'.
Re^3: Read the csv file to a hash....
by whereiskurt (Friar) on Jul 07, 2007 at 14:13 UTC

    I should probably just /msg you, but I had to say, that this construct:

    { local $_ = <DATA>; chomp; .. }

    Is wicked. SO MANY TIMES I've re-invented the wheel and created little stupid variable names.. yadda yadda. Never agian. I will localize the scope on $_ and us it as a temporary string manipulation variable.. Thanks for doing that guys homework so well! :-)

    Kurt

    PS: I really have to echo PBP on this: Use Text::CSV_XS to extract complex variable-width fields. - DCFB