如何在 Perl 的 fetchall_arrayref foreach 循环中获取数组的最后一个元素?

问题描述

我在 MySql 中使用 Perl。我有一个查询,我正在使用 fetchall_arrayref 从我的调查应用程序中获取结果数据。按照文档的建议,我使用 foreach 循环遍历 fetchall_arrayref。在这个循环中,我遍历 $answer1 数据并运行一个计数器来计算一个问题的所有答案,我想要总数。当我将此信息推送到数组中并尝试获取该数组中的最后一个元素时,我没有得到所需的输出。我在我的 fetchall_arrayref foreach 循环之外运行了一个测试,使用相同的逻辑,它成功地获得了我需要的东西。

这是我的代码:

my $testQuery = "SELECT questionNum,question,answer1 FROM results WHERE title = ? ORDER BY questionNum";
my $sty = $dbh->prepare($testQuery);
$sty->execute($marathon);
my $potential = $sty->fetchall_arrayref();
$sty->finish;

my $previous_question;
my $previous_answer;
my $countEm;
my @total;
my @totalAnswer;
my @norm;
my $last_arr_index;
foreach my $data (@$potential) {
    my ($questionNumber,$question,$answer1) = @$data;
    $answeredOne = 0;
    print qq{<tr><td>$questionNumber. $question</td></tr>} unless $previous_question eq $question;
    if ($answer1 ne "" && $questionNumber == 1){
        $optionOne = $answer1;
        $answeredOne = $answeredOne + 1;
        $countEm++;
        push @total,$countEm;
        push @totalAnswer,$optionOne;
    }
    if ($answeredOne != 0){
        #my $elementCount = scalar(@total);
        #say $elementCount;
        say @total[-1];
    }

$previous_question = $question;
$previous_answer = @totalAnswer[2];
}#end foreach

当我打印时:“说@total[-1];”当我只需要“3”时,给我“1 2 3”的输出。

我在 fetchall_arrayref foreach 循环之外测试了同样的逻辑,我得到了想要的输出:

my $counting;
my @totalCounting;
my @link = ('water','water','water');
foreach my $i (@link){
    $counting++;
    push @totalCounting,$counting;
}
say @totalCounting[-1];

"说 totalCounting[-1];"给我“5”。

为什么这在 fetchall_arrayref 中不起作用?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)