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.


Perl reduces RSI - it saves typing

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.