in reply to Repeat question

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

Replies are listed 'Best First'.
Re^2: Repeat question
by davido (Cardinal) on Dec 02, 2018 at 02:42 UTC

    Even though I posted an answer that uses the same module I upvoted this node because it was nice to see that same module used in a slightly different way. (Plus I was pleased to see that someone besides me is aware of the module's existence.)

    In a future version of the module I intend for validation failures to stash additional information that error can retrieve from its parameter list so that error doesn't need to try to figure out all over again why validate failed. ...so something of a try/catch notion.


    Dave