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.


In reply to Multiple references pointing to the same memory location by ezekiel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.