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

Maybe I am going about this wrong, but I think there should be a way to do this. I want to have a hash of array reference so I have the following code snippet: <OUTSIDE LOOP> undef(@selections); while ((my $choice) = $sth->fetchrow_array()) { push(@selections,$choice); } $selections{$_} = \@selections; <END OUTSIDE LOOP> The result of this is that when I undef the array to clear in preparation for the next iteration, I also undef the ref from the previous iteration(s). Then the next ref is created and all values in the hash are the same reference which happens to be the last reference used. So, how do I build an array, put the ref into a hash and then loop back again so I can build up the next array to make a ref to put in the hash and so on.

Replies are listed 'Best First'.
(Ovid) Re: Array Ref Problem
by Ovid (Cardinal) on Dec 29, 2001 at 04:52 UTC

    Simplest is to drop the useless array. Also, you want $sth->fetchrow_arrayref.

    while ((my $choice) = $sth->fetchrow_arrayref()) { push(@{ $selections{$_} },$choice); }

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      Right you are. Thanks.
Re: Array Ref Problem
by thor (Priest) on Dec 29, 2001 at 21:57 UTC
    I also noticed the following:

    while ((my $choice) = $sth->fetchrow_array())

    You are fetching an array, but storing it in a scalar. You probably want to use the fetchrow_arrayref method. Keep in mind that you cannot simply push the array reference on to an array and hope to use it later, because as I understand it, that method reuses the same array reference on each fetch. In other words, you will get the same array many times when you try to dereference it.
      Okay, here is it new's years eve and I am writting code. I think I should get extra XP just for that alone : ) Anyway, what I came up with was: <OUTER LOOP> { undef(@selections); while ((my $choice) = $sth->fetchrow_array()) { push(@{ $selections{$_} },$choice); } } <END OUTER LOOP> I tried that arrayref idea, but then I had to deference it again and it just seemed unnecessary unless I misunderstood what you were trying to say. Anyway, this all worked great and I thank all who helped out.