1

Below is a snippet of Perl code. I would like to loop through several queries with different regular expression ($myo) and for different operators ($op) and save the results to an array of arrays rather than one large @result array.

I.e., the array of results for MYO[0-9]*$ would be an array for each operator $results[0][0], $results[0][1] ... and for MYO[0-9]*R$, $results[1][0], $results[1][1].

Any ideas?

my @tech_ops =  ("AR","DB","GM","LW","MM","SA");
  my @results;

    for my $myo (qw(MYO[0-9]*$ MYO[0-9]*R$ MYO[0-9]*T$ MYO[0-9]*U$)) {
      foreach $op (@tech_ops)
        {
           $sth->execute($myo, $date_stop, $date_start,$op) 
         or die "Couldn't execute query for $myo: " . $sth->errstr;
           push @results, $sth->fetchrow_array;
         }
    }
2
  • I'm guessing that your SQL is only returning one column; if not, do you really want an array of arrays of arrays? Commented Jan 18, 2013 at 17:38
  • The array of array idea was to make it easier to populate the results into a latex table using a for loop. Probably not the most efficient solution but the first one i came up with Commented Jan 18, 2013 at 17:51

3 Answers 3

6

Use the fetchall_arrayref method instead of the fetchrow_array method.

So just replace this line:

push @results, $sth->fetchrow_array;

With this line:

push @results, $sth->fetchall_arrayref;

Here is the documentation for all the DBI statement handler methods.

Sign up to request clarification or add additional context in comments.

Comments

4
my @tech_ops =  ("AR","DB","GM","LW","MM","SA");
my @results;

for my $myo (qw(MYO[0-9]*$ MYO[0-9]*R$ MYO[0-9]*T$ MYO[0-9]*U$)) {
    my @myo_results;
    foreach $op (@tech_ops) {
        $sth->execute($myo, $date_stop, $date_start,$op) 
            or die "Couldn't execute query for $myo: " . $sth->errstr;
        push @myo_results, $sth->fetchrow_array;
    }
    push @results, \@myo_results;
}

Comments

0

You could just use an array reference:

my $ref;
for my $i (1..10) {
   for my $j (1..10) {
        push @{$ref->[$i]}, $j;
    }
}

That will do it.

EDIT: This will create a reference to a 10x10 matrix.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.