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

I'm not even sure I'm using the correct terminology, but here's the scenario. I'm looping through a series of ids to fetch MySQL records into AoH's, each of which must be pushed into a 'final' AoH for use in an HTML::Template loop. I kept getting the error:

Type of arg 1 to push must be array (not private variable) at searchnews.pl line 52, near "@shows)"

My code snippet

my ($stmt, $shows, $allshows); for my $i ( 0 .. $#ids ) { $stmt = "SELECT * FROM shows WHERE id = '$ids[$i]'"; &execute_it( $stmt ); #sub that prepares and executes while ($shows = $sth->fetchall_arrayref({})) { push ($allshows, $shows); } } print Dumper ($allshows);

I understand pushing elements into arrays, but can you push AoHs in to AoHs and how do I keep the reference status for the HTML::Template loop? Is this even possible, or is there a different approach? Thanks all.


—Brad
"Don't ever take a fence down until you know the reason it was put up." G. K. Chesterton

Replies are listed 'Best First'.
Re: Pushing AoH refs into another AoH ref
by NetWallah (Canon) on Sep 02, 2004 at 05:33 UTC
    japhy's answer (@$allshows) is correct - however it raises the question - why would you want to do it that way - it seems to complicate life without adding value.

    Why not just declare my @allshows and push directly into it ? The only good reason NOT to declare it as an array is - if it was passed-in as an array ref, in which case japhy's syntax is a reasonable way to go.

        Earth first! (We'll rob the other planets later)

      Points well taken. I have amended my code, and it works great. Thanks all.

      my ($shows, $allshows); for my $i ( 0 .. $#ids ) { $stmt = "SELECT * FROM shows WHERE type = 2 AND id = '$ids[$i]'"; $sth = $dbh->prepare($stmt); $sth->execute(); push @$allshows, $sth->fetchall_arrayref({}); }

      —Brad
      "Don't ever take a fence down until you know the reason it was put up." G. K. Chesterton
Re: Pushing AoH refs into another AoH ref
by japhy (Canon) on Sep 02, 2004 at 03:12 UTC
    I question the copying and pasting of your code, but I believe all you need to do is change your line to: push @$allshows, $shows; But actually, that's not good enough, because you're always populating the same variable. So do:
    for (@ids) { my $stmt = "SELECT * FROM shows WHERE id = '$_'"; &execute_it( $stmt ); #sub that prepares and executes while (my $shows = $sth->fetchall_arrayref({})) { push @$allshows, $shows); } }
    _____________________________________________________
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart