迭代从 fetchall_arrayref 返回的结果
Iterating the results returned from fetchall_arrayref
我有一个sql,其中我正在获取几条记录,按全名排序。
我的需求是提取相似名字的块,然后对其进行一些操作。
比如说,sql returns 一些记录包含像 [name1,name1,name2,name3,name3]
这样的名字
我需要将它们拆分为 [name1,name1] , [name2] , [name3,name3]
我可以做到,但我对我的实现不满意,因为我必须调用 doSomethingWithNames()
两次。
while (my $paRecs = $pStatementHandle->fetchall_arrayref({}, 3)){
foreach my $phRec(@{$paRecs}){
my $pCurrentName = $phRec->{'FULL_NAME'};
if ((scalar(@aParentRecords) eq 0) or ($aParentRecords[-1] eq $pCurrentName)){
push(@aParentRecords, $pCurrentName);
} else {
doSomethingWithNames(\@aParentRecords);
@aParentRecords= ();
push(@aParentRecords, $pCurrentName);
}
}
};
doSomethingWithNames(\@aParentRecords); # This should be inside while loop
我相信我 运行 关注这个问题,因为 while 不会进入循环 for
最后一次迭代为 fetch*
returns undef
.
听上去是基本的 PERL 东西,但是尝试了很多循环构造都没有成功。
任何指针都会有很大的帮助
诀窍是通过将现有循环转换为无限循环来推迟现有循环。不过,这需要检查循环终止条件 (!$rows
) 两次。
my $rows = [];
my $prev_name = '';
my @group;
while (1) {
$rows = $sth->fetchall_arrayref({}, 3) if !@$rows;
if (!$rows || $rows->[0]->{FULL_NAME} ne $prev_name)
if (@group) {
do_something(\@group);
@group = ();
}
last if !$rows;
}
$prev_name = $rows->[0]->{FULL_NAME};
push @group, shift(@$rows);
}
我有一个sql,其中我正在获取几条记录,按全名排序。
我的需求是提取相似名字的块,然后对其进行一些操作。
比如说,sql returns 一些记录包含像 [name1,name1,name2,name3,name3]
我需要将它们拆分为 [name1,name1] , [name2] , [name3,name3]
我可以做到,但我对我的实现不满意,因为我必须调用 doSomethingWithNames()
两次。
while (my $paRecs = $pStatementHandle->fetchall_arrayref({}, 3)){
foreach my $phRec(@{$paRecs}){
my $pCurrentName = $phRec->{'FULL_NAME'};
if ((scalar(@aParentRecords) eq 0) or ($aParentRecords[-1] eq $pCurrentName)){
push(@aParentRecords, $pCurrentName);
} else {
doSomethingWithNames(\@aParentRecords);
@aParentRecords= ();
push(@aParentRecords, $pCurrentName);
}
}
};
doSomethingWithNames(\@aParentRecords); # This should be inside while loop
我相信我 运行 关注这个问题,因为 while 不会进入循环 for
最后一次迭代为 fetch*
returns undef
.
听上去是基本的 PERL 东西,但是尝试了很多循环构造都没有成功。 任何指针都会有很大的帮助
诀窍是通过将现有循环转换为无限循环来推迟现有循环。不过,这需要检查循环终止条件 (!$rows
) 两次。
my $rows = [];
my $prev_name = '';
my @group;
while (1) {
$rows = $sth->fetchall_arrayref({}, 3) if !@$rows;
if (!$rows || $rows->[0]->{FULL_NAME} ne $prev_name)
if (@group) {
do_something(\@group);
@group = ();
}
last if !$rows;
}
$prev_name = $rows->[0]->{FULL_NAME};
push @group, shift(@$rows);
}