简体   繁体   English

如何使用Perl推入数组数组?

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

Below is a snippet of Perl code. 下面是Perl代码的片段。 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. 我想遍历具有不同正则表达式( $myo )和不同运算符( $op )的几个查询,并将结果保存到数组数组而不是一个大@result数组。

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] . 即, MYO[0-9]*$ $results[0][0]数组将是每个运算符$results[0][0]$results[0][1] ...和MYO[0-9]*R$的数组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. 使用fetchall_arrayref方法而不是fetchrow_array方法。

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. 这是所有DBI语句处理程序方法的文档。

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. 编辑:这将创建对10x10矩阵的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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