I'm using Perl with MySql. I have query that I'm using with fetchall_arrayref to grab results data from my survey application. As recommended by documentation I use foreach to loop through fetchall_arrayref. Inside of this loop, I loop through my $answer1 data and run a counter to count all of the answers for a question and I want the total. When I push this information into an array and try to grab the last element in that array, I don't get the desired output. I ran a test outside of my fetchall_arrayref foreach loop, using the same logic and it was successful in getting me what I needed.
Here's my code:
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]; }
没有评论:
发表评论