The module IO::Prompt::Hooked verifies the answer and reprompts if wrong. It also provides a convenient way for the user to exit the program.
$type hchana.pl use strict; use warnings; use IO::Prompt::Hooked; srand(999); # Delete for production my $correct_ans; my %opt = ( escape => qr/q(uit)?/i, # Type 'quit' to exit program error => "Sorry you're wrong, have another go.\n\n", validate => sub { $_[0] !~ /\D/ and $_[0] == $correct_ans}, ); while (1) { my $random_integer1=int(rand(100)); my $random_integer2=int(rand(100)); my $sign = ($random_integer1 > $random_integer2) ? '-' : '+'; $correct_ans = $random_integer1 + (($sign eq '+') ? $random_integer2 : -$random_integer2); my $msg = "What is $random_integer1 $sign $random_integer2?"; my $ans = prompt( message => $msg, %opt ); last if !defined $ans; print "Well done.! $ans is correct.\n\n"; } warn "Program terminated by user\n"; $perl hchana.pl What is 10 + 63? 73 Well done.! 73 is correct. What is 80 + 92? too hard Sorry you're wrong, have another go. What is 80 + 92? 22 Sorry you're wrong, have another go. What is 80 + 92? 172 Well done.! 172 is correct. What is 77 - 53? 44 Sorry you're wrong, have another go. What is 77 - 53? 24 Well done.! 24 is correct. What is 59 - 41? quit Program terminated by user $

UPDATE: Started this yesterday. Did not notice that Dave had posted a similar solution while I was sleeping. Note that this version does handle sign the same as the OP.

Bill

In reply to Re: Repeat question by BillKSmith
in thread Repeat question by hchana

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.