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
    $hrec{'Comments'} = \@names; $hrec{'Names'} = \@comments;
    Any reason to switch the keys and values? :-)
    Another solution would be to store the pairs "Name / Comment" in a simple hash
    ... unless the OP really needs to preserve the order. While I don't see the importance, it could be that way it has to, whatever the reason the person who gave the assignment (if it is).

    Update

    the best solution would be using Text::CSV_XS
    I'd say that the core problem is arranging the data structure, not parsing the source file. While using that module might be one of the best among its competitors, it does solve only half the problem.

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