[英]How do I use Perl to push into an array of arrays?
下面是Perl代码的片段。 我想遍历具有不同正则表达式( $myo
)和不同运算符( $op
)的几个查询,并将结果保存到数组数组而不是一个大@result
数组。
即, 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]
。
有任何想法吗?
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;
}
}
使用fetchall_arrayref
方法而不是fetchrow_array
方法。
因此,只需替换此行:
push @results, $sth->fetchrow_array;
用这行:
push @results, $sth->fetchall_arrayref;
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;
}
您可以只使用数组引用:
my $ref;
for my $i (1..10) {
for my $j (1..10) {
push @{$ref->[$i]}, $j;
}
}
这样就可以了。
编辑:这将创建对10x10矩阵的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.