HiFoo has asked for the wisdom of the Perl Monks concerning the following question:

I'm really confused. I have a class that contains a hash of arrays in the my new function:
sub new { ... ... $self->{TABLE}{6} = ("4", foo", "was", "here"); $self->{TABLE}{3} = ("3", foo", "was", "here"); ... ... bless ( $self, $class); return $self;
When I try to access the arrays in the hash using something like:
my @foo = @{ $self->{TABLE}{6} }; print "$foo[0]\n";
I get the error:
Can't use string ("here") as an ARRAY ref while "strict refs" in use at ./test.pl line x.

and the string in mention is always the last element in the array.

What I don't understand is why I get a scalar value when I think I should be getting an array. Am I incorrectly adding the arrays to the hash or am I doing something else wrong?

Thanks

Replies are listed 'Best First'.
Re: Trouble with Hashes of Arrays
by thelenm (Vicar) on Aug 14, 2002 at 19:56 UTC
    Your assignments are incorrect... you should be assigning list anonymous array references instead of lists themselves. In this context, you are actually assigning the last element of the list, not the list itself. Try this instead:
    $self->{TABLE}{6} = [ "4", "foo", "was", "here" ]; $self->{TABLE}{3} = [ "3", "foo", "was", "here" ];

    -- Mike

    --
    just,my${.02}

Re: Trouble with Hashes of Arrays
by mfriedman (Monk) on Aug 14, 2002 at 20:29 UTC
    There really isn't any such thing as a hash of arrays in Perl. Your hash must contain references to arrays. You can do that by assigning an anonymous array reference:

    $hash{'foo'} = [ 1, 2, 3, 4 ];

    Or by assigning a reference to an existing array:

    $hash{'foo'} = \@bar;

Re: Trouble with Hashes of Arrays
by BorgCopyeditor (Friar) on Aug 14, 2002 at 21:08 UTC

    On an unrelated note, it looks like you're using numbers as hash keys, e.g., "6":

    $self->{TABLE}{6}

    Shouldn't this be an array, à la $self->{TABLE}[6]? Might save you some space and give you more natural (i.e., numerically indexed) access to your data. Maybe that's just superstition on my part; I like to keep numbers and strings strictly separated, but Perl typically handles the translations seamlessly, especially for integers.

    BCE
    --Your punctuation skills are insufficient!