sub isAnInt { ($input) = @_; if($input =~ /^[+-]?\d+$/){ return true; } return false; } sub getNumericInput { ($prompt) = @_; while(true) { print $prompt; print ": \r\n"; $ans = <>; chomp($ans); if(isAnInt($ans) eq true) { return int($ans); } print "Your entry was not a number.\r\n"; } } sub getInput { ($question) = @_; while(true) { print $question; print "?\r\n"; $ans = uc <>; chomp($ans); if($ans ne "") {return $ans;} print "Your entry seem empty.\r\n"; } } sub askToPlayAgain { while(true) { $ans = getInput("Would you like to play again? (\"YES\" or \"NO\")"); if($ans eq "YES" || $ans eq "Y") {return true;} if($ans eq "NO" || $ans eq "N") {return false;} print "Please respond with \"YES\" or \"NO\".\r\n"; } } $running = true; $gotMaxNumber = false; $maxNumber = 0; $answer = 0; $gameover = false; $tries = 0; print "*** GUESS A NUMBER : Perl\r\n"; while($running eq true) { while($gotMaxNumber eq false) { $maxNumber = getNumericInput("Please enter the maximum number you wish to use"); if($maxNumber gt 0) { $gotMaxNumber = true; $answer = int(rand($maxNumber)) + 1; $gameover = false; $tries = 0; print "Ok, I am thinking of a number between 1 and ", $maxNumber, ".\r\n"; } else { print "The maximum number should be greater than zero.\r\n"; } } $guess = getNumericInput(sprintf "Guess a number between 1 and %d", $maxNumber); $tries++; if($guess gt $answer){ print "Too high.\r\n";} if($guess lt $answer){ print "Too low.\r\n";} if($guess eq $answer) { if($tries eq 1){print "You got it in 1 try!\r\n";} else {print "You got it in ", $tries, " tries!\r\n";} $gameover = true; } if($gameover eq true) { $running = askToPlayAgain(); if($running eq true) { $gotMaxNumber = false;} } } print "Thanks for playing!\r\n"; print "*** GAME OVER ***\r\n";