in reply to Regarding Hashes of Arrays

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.

Replies are listed 'Best First'.
Re^2: Regarding Hashes of Arrays
by hardburn (Abbot) on Aug 10, 2004 at 20:16 UTC

    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.

    The fact that there is a multi-dimentional datastructure should already make it assumed there are references involved. Or do you know of a way to do complex datastructures in Perl without references?

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

        /me shudders at code above

        I still say the -> is unnecessary, since if you're using real datastructures in Perl, the references part should be assumed.

        "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.