简体   繁体   中英

How do I use Perl to push into an array of arrays?

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.

Ie, 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;
         }
    }

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.

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM