in reply to Re: Number Guess
in thread Number Guess

Wow, truly the monks are wise and patient. Thanks for the great advice.

Yes, I had some sense that goto might be a little hacky, but I didn't know how to use subroutines. Obviously, they are the magic answer I needed. Also, I did use strict and use warnings while I was working on this, but after I knew it would work, I didn't bother pasting them in here--why? Who knows; however, I now see the error of my ways.

Looking at your for loop, I have a question. How does this handle the situation in which the player does successfully guess the answer in under ten tries? Since you have set the loop to run ten times, it looks like it will print "you have x guesses left" and wait for guess input even after you have won the game. I have just run the code and seen that this is not the case, but I can't figure out why. (Also, it looks like the "guesses left" line needs to be removed from the if statements, since you have put it at the top of the for loop. But this is a simple matter.)

Here is another question: why do I have to chomp $again, but not chomp $guess?

Replies are listed 'Best First'.
Re^3: Number Guess
by Tanktalus (Canon) on Jul 15, 2005 at 20:41 UTC

    Question 1: guessing the answer in under 10 tries. The statement you missed is "return". It causes the subroutine to return to whoever called it immediately. All loops that it may be in at that point are automatically exited directly to the caller, bypassing any and all other statements in the subroutine.

    Question 2: chomping. Your $guess is a number. Perl's DWIMery trick with numbers is to treat anything that looks like a number as a number. So if you have a string such as "12afsd4583", perl will treat it as the number 12. e.g.,

    $ perl -e 'print 0+"12afsd4583";print $/' 12
    In your case, the string $guess really is "123\n". Perl sees the "123" part as a number, and then it sees stuff that isn't numeric and cuts it off at that point. So it will do an implicit 'chomp'-like action.

    However, with $again, you're comparing it with the eq operator. Perl can't know, based on string context, whether the \n is important or not, so you have to be explicit. Another way to avoid the chomp is to use a less-precise match, such as a regular expression, e.g., $again =~ /y/i will match anything with a 'y' or a 'Y' in the string, whether it's followed by a carriage return or not.

    BTW - I pointed out the strict comment because while I was rewriting your code (or, rather, mostly just reformatting), I came upon a problem that would have been caught sooner had strict been used. Not a problem in your code, but in an intermediate code between what you had and what I ended up with. ;-) Another advantage of using strict when it's not necessarily needed: adding features and refactoring become easier. Or at least safer. ;-)

      Thanks for your help!