They're both incorrect. If you'd use warnings you'd get a warning from the first construct.

$hash{$id} = (1,2,3); will set $hash{$id} = 3 (the last element in the list).

and $hash{$id} = @temp; will set $hash{$id} = 3 (the length of @temp).

You cannot literally make a hash with arrays as the values in Perl, you need array-references:

$hash{$id} = [1,2,3]; # [ ... ] creates an anonymous array ref @temp = (1,2,3); $hash{$id} = \@temp; # \ makes an explicit reference to @temp
Note that \(1,2,3) will make a list of references to 1, 2 and 3, so don't use that.

If you want to read one of the values from the array ref you do:

$x = ${$hash{$id}}[0]; # or $x = $hash{$id}[0]; # or $x = $hash{$id}->[0];

I like the last syntax best, because it makes it clear that there is a reference (more or less equivalent to a "pointer" in C speak) involved.

If you want to whole list of values from the array, you can do:

my @values = @{$hash{$id}};
perlref has a lot of info about this.


In reply to Re: Regarding Hashes of Arrays by Joost
in thread Regarding Hashes of Arrays by Anonymous Monk

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.