in reply to Number Guess
#!c:\perl\bin\perl.exe -w # -w means "warn me if I do anything that i may not want to do (ie: ma +ke a typo in a var name)" use strict; #Because God wants it my $guess; #declare it somewhere like here seems nice TOP: my $tries = 10; my $value = int(rand(200)); print "Pick a number between 0 and 200.\nYou have ",$tries--," guesses + left.\n"; #Do it in one line. #the $tries-- prints $tries and then, decrements it. while ($tries>0 and defined ($guess=<STDIN>)){ #since you reread $guess each time, why not write it just once? #then until became a while, so I inversed the $tries test too. #defined is used because the <STDIN> can be undefined... #put the $tries test first, so that it doesn't ask for input when yo +u're over next if $guess!~m/^\d+\n$/; #this might be a bit ugly right now #just learn this as "it is an integer followed by a carriage return" + #And then, read about regexps if($guess>$value){ print "You need to guess a lower number.\nGuesses left: ",$tries-- +,"\n"; next; # jump again to the while loop NOW #same hacks as above. } if($guess<$value){ print "You need to guess a higher number.\nGuesses left: ",$tries- +-,"\n"; next; #same hacks as above. } #beeing here means we didn't jumped before (the "next"'s were not ca +lled print "You guessed my number in ",(10-$tries)," guesses. Thanks for +playing.\n"; $tries=0; } print "Sorry, you ran out of guesses. My number was $value\n" if ($gu +ess != $value); #Since the test is a "simple" if (this) then {just that} #you can write just that if (this); #looks like English. Easy to read. print "Play Again? (y/n) \n"; chomp(my $again = <STDIN>); #chomp ($again); goto TOP if($again =~m/y/i);#I don't like goto, but that's your code. #=~ means check this var #m/foo/ means "does it contain the word foo" #i means case insensitive #once again, the if can be written easier #else not needed! print "Goodbye!";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Number Guess
by cryptoquip (Novice) on Jul 15, 2005 at 21:11 UTC |