in reply to Read the csv file to a hash....
So, you want to store all the 'Names' in an array and all the 'Comments' in another array, and put both in a hash, right?
So, you are thinking in something like:
use strict; use warnings; my @names; my @comments; my %hrec; while (<DATA>){ chomp; my ($name,$comment) = split ","; $name =~ s/"//g; $comment =~ s/"//g; push @names,$name; push @comments,$comment; } $hrec{'Names'} = @names; $hrec{'Comments'} = @comments;
But this doesn't work, because you can not put an array in a hash entry, only a scalar, so in the hash you will have to store a reference to an array:
# $hrec{'Names'} = @names; # $hrec{'Comments'} = @comments; $hrec{'Comments'} = \@names; $hrec{'Names'} = \@comments;
Because in the hash there are references to arrays instead of arrays, the syntax to access their elements are a bit different:
$hrec{'Names'}->[0]; ## Isha $hrec{'Comment'}->[0]; ## Hello!! ;
Another solution would be to store the pairs "Name / Comment" in a simple hash, like:
my %hrec; while (<DATA>){ chomp; my ($name,$comment) = split ","; $name =~ s/"//g; $comment =~ s/"//g; $hrec{$name} = $comment; }
See perlreftut and perlref for more info about references
Said all that, I agree with tirwhan and GrandFather, the best solution would be using Text::CSV_XS.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Read the csv file to a hash....
by naikonta (Curate) on Jul 06, 2007 at 17:16 UTC |