in reply to Adding an AoH to an AoH

You are storing multiple references to the same variable into your structure, but you meant to store references to different arrays.

for my $i ( 0 .. $#$proj ) { my $time = $dbh->selectall_arrayref($stmt, {Slice => {}}, $project_ +id); my @users; # Create a new array every pass through the loop. for my $j ( 0 .. $#$time ) { push @users, $time->[$j]; } $proj->[$i]{'users'} = \@users; }

By the way, undef @users; is also a bug, since it clears both @users and @{ $proj->[$i]{'users'} } since they're the same variable.

Update: The above code can be simplified to

for my $i ( 0 .. $#$proj ) { my $time = $dbh->selectall_arrayref($stmt, {Slice => {}}, $project_ +id); $proj->[$i]{'users'} = $time; }

Replies are listed 'Best First'.
Re^2: Adding an AoH to an AoH
by Fletch (Bishop) on Jan 21, 2008 at 04:39 UTC

    Just a word of caution: do not directly store off the returned reference from DBI results from other methods without first checking the docs to see if it's safe to do so.

    Most likely to be hit in "normal" use would be fetchrow_arrayref which reuses the same underlying array for each call (so you'd need to dereference and make a copy; e.g. $store->{'somewhere'} = [ @{ $returned_by_fetchrow_arrayref } ];).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re^2: Adding an AoH to an AoH
by bradcathey (Prior) on Jan 21, 2008 at 12:58 UTC

    Thanks ikegami for pointing out that very subtle bug of the undef and suggesting just recreating the @users array for each pass. Brilliant. I don't know if I would have ever seen that. Anyway, all is well and working as hoped.

    Which brings up another point: create a test that really emulates the actual application. In this case my test was too sanitized and would never have shown me the problem.

    —Brad
    "The important work of moving the world forward does not wait to be done by perfect men." George Eliot

      Indeed. Minimizing the code is a great way of isolating a problem.

      Another good way of finding sticky problems is trying to describe the problem to someone else. Follow the description by as man "It can't be X because I tried Y." as you can think of. When doing so, I usually come up with Xs I hadn't handled.