Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^3: Number Guess

by Tanktalus (Canon)
on Jul 15, 2005 at 20:41 UTC ( [id://475356]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Number Guess
in thread Number Guess

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. ;-)

Replies are listed 'Best First'.
Re: Number guess
by cryptoquip (Novice) on Jul 15, 2005 at 21:55 UTC
    Thanks for your help!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://475356]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (7)
As of 2024-04-23 12:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found