If possible it is a really good idea to keep related data together so that it can be handled in a common fashion. Perl lets you do that by using structures like arrays of array and hashes etc. In your case it makes sense that you keep the question and answer pairs together. You could use an array for each pair, but it's easier to understand the code if you use a hash instead. Consider:
use strict; use warnings; my @quiz = ( {ask => "Name the definitive rock band..", answer => "The Rolling Stones" }, {ask => "What is their best song?", answer => "Moonlight Mile" }, {ask => "What is their best album?", answer => "Sticky Fingers" } ); my @incorrect; for my $question (@quiz) { print "$question->{ask}: "; my $guess = <STDIN>; chomp $guess; if (lc $guess eq lc $question->{answer}) { print "You Rock!\n"; } else { print "You Suck!\n"; # if incorrect, reply and save answer to + be calculated push @incorrect, [$question, $guess]; } } my $grade = (@quiz - @incorrect) / @quiz * 100; print "Grade: $grade\n";
Note that there is now no need for a counter to access the question and answer. Because each question and answer is paired it is trivial to add questions or change their order and know that the right answer is matched with each question.
Note too that now the entire question and answer are stored along with the answer given in the incorrect list. Also the grade uses the count of elements in the two arrays for the calculation so that a manually calculate constant isn't required - the grade calculation remains correct if the number of questions changes.
In reply to Re: Control Structure problem, mistake can't be found
by GrandFather
in thread Control Structure problem, mistake can't be found
by koolgirl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |