Lewisa has asked for the wisdom of the Perl Monks concerning the following question:
Here's my code:
When I print: say @total[-1]; gives me the output of "1 2 3" when I just need "3".my $testQuery = "SELECT questionNum, question, answer1 FROM results WH +ERE 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 $pre +vious_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
I tested this same logic outside of the fetchall_arrayref foreach loop and I got the desired output:
say totalCounting[-1]; gives me "5".my $counting; my @totalCounting; my @link = ('water', 'water', 'water', 'water', 'water'); foreach my $i (@link){ $counting++; push @total``Counting, $counting; } say @totalCounting[-1];
Why won't this work inside of fetchall_arrayref?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How can I get the last element of an array inside of fetchall_arrayref?
by hippo (Archbishop) on Mar 23, 2021 at 17:47 UTC | |
by Lewisa (Novice) on Mar 23, 2021 at 17:57 UTC | |
by hippo (Archbishop) on Mar 23, 2021 at 18:45 UTC | |
by Lewisa (Novice) on Mar 23, 2021 at 20:09 UTC | |
by Lewisa (Novice) on Mar 24, 2021 at 01:20 UTC | |
|
Re: How can I get the last element of an array inside of fetchall_arrayref?
by choroba (Cardinal) on Mar 23, 2021 at 18:05 UTC | |
by Lewisa (Novice) on Mar 23, 2021 at 18:09 UTC |