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


In reply to Re^3: Number Guess by Tanktalus
in thread Number Guess by cryptoquip

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.