ezekiel has asked for the wisdom of the Perl Monks concerning the following question:
I have a subroutine that works like this:
# Loop over a series of keys foreach $key (@keys) { # Use the key to do a database lookup $sth->execute($key); # Get the results of the lookup ie all the entries in # the row keyed by the key. $columns_ref = $sth->fetchrow_arrayref(); # Push this reference onto another array to build up # an array of the rows corresponding to each key push(@entries, $columns_ref); }
Later on I want to loop through @entries and use each reference to access each row in turn. Everytime I execute the statement handle, the array returned is stored in the same memory location ($columns_ref). Hence at the end of the loop @entries looks something like:
(Array(0x8057040), Array(0x8057040), Array(0x8057040), ... )
So when I loop over @entries later, I get the same memory location and hence the same (last) row over and over, rather than each row in turn.
Is there a way to get around this? I am sure there is a simple solution but I just can't see it at the moment.
I have tried the following:
foreach $key (@keys) { $sth->execute($key); $temp_columns_ref = $sth->fetchrow_arrayref(); @temp_columns = @$temp_columns_ref; $columns_ref = \@temp_columns; push(@entries, $columns_ref); }
This works but it is ugly and I am worried about the memory/performance involved in creating the copy of the array (@temp_columns) as there are generally a large number of rows each with a large amount of data.
Any comments on the memory implications of references versus array would also be helpful as my understanding of this area is limited.
Thanks.
|
|---|