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.


In reply to Re: Read the csv file to a hash.... by citromatik
in thread Read the csv file to a hash.... by isha

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.