Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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

by snopal (Pilgrim)
on Jul 06, 2007 at 15:58 UTC ( [id://625287]=note: print w/replies, xml ) Need Help??


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

Is there any reason that the following structure would be inappropriate?
#!/usr/bin/perl -w use strict; use Text::CSV_XS; my $fh; unless (open $fh, "filename") { die "No file available\n"; } my $csv = Text::CSV_XS->new({binary => 1}); my @people; <$fh>; # Drop column names on the floor while ( my $line = <$fh> ) { my $status = $csv->parse($line); my @columns = $csv->fields(); my %h; @h{('Name','Comment')} = @columns; push @people, \%h; } close $fh; print "Name: " . $people[2]->{'Name'} . ", Comment: " . $people[2]->{'Comment'} . "\n";

It seems to me that keeping the associated data together is a better solution to this problem. Also, looping by key field is more flexible than looping by dedicated array name.

Replies are listed 'Best First'.
Re^2: Read the csv file to a hash....
by RMGir (Prior) on Jul 06, 2007 at 16:16 UTC
    That's reasonable, but I'd think that instead of
    <$fh>; # Drop column names on the floor
    the script should read that and parse it, so it gets the column names from the .csv file rather than hardcoding Name and Comment.

    Apart from that, that works very nicely, and Text::CSV_XS is much more robust than my //g approach above.


    Mike

      I agree wholeheartedly that a production system should use all available data. Your point is extremely valid. I have almost always applied column header preservation in my production environments.

      I made a design decision here so that I could highlight the storage strategy here over the complexity of the implementation (yet showing off a bit with the assignment).

Re^2: Read the csv file to a hash....
by naikonta (Curate) on Jul 06, 2007 at 17:09 UTC
    <$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!

      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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-20 00:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found