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

Hi, I'm having trouble with an array of references. I'm reading rows from a MySQL database, and using fetchrow_arrayref to get a reference to an array containing each field. I'm then trying to push this reference onto another array called @returnme, which ends up holding a reference to an array for each of the rows returned. This is the code I have:
while ($result = $sth->fetchrow_arrayref) { $before.= $$result[0]; push (@returnme, $result); } $after.= ${$returnme[0]}[0]; $after.= ${$returnme[1]}[0];
(There are only 2 records in the DB right now.) When I display the contents of $before, I get the values of the first field of each returned row. But when I display the contents of $after I just get the first field of the second row, repeated twice. Also, I tried changing the first value directly with ${$returnme1}[0] = "HI"; which results in $after returning "HIHI" instead of only modifying one value - the same happens if I go for element 0 instead of 1. It can't be a referencing problem if it works both ways right? I have no idea why this is happening, if anyone could give me some advice that would be fantastic.

Replies are listed 'Best First'.
Re: Crazy array of references behavior
by shenme (Priest) on Dec 01, 2003 at 15:32 UTC
    Reread the DBI docs on fetchrow_arrayref():
    Note that the same array reference is returned for each fetch, so don't store the reference and then use it after a later fetch.
      Thanks man, I see what's going on now - I'm just storing a bunch of references to one single array. Time for a rethink about how to do this :)
Re: Crazy array of references behavior
by dragonchild (Archbishop) on Dec 01, 2003 at 18:05 UTC
    shenme has the reason why it's not working. However, that doesn't lead you away from the Dark Pit. The clue you need, Anonymonk, is to copy off the values to some other place, preferably a data structure that is useful in later code. This can be considered a "munge" section of the WMD (Wread-Munge-Dump) architecture. (Some people erroneously call it ETL ... WMD is much cooler - even the President likes the term!)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      Ah, but the trouble with WMD is that they're often 404 :)

      .02

      cLive ;-)

      Thanks guys - I cracked open one of those book things and read up on anonymous data structures, and everything's going great! For now.