As GrandFather said in the CB, you need while, next and last.

You should also add use strict; and use warnings; to the top of all your scripts. Without going into any great detail here, these will basically let you know if you've done something wrong.

You also need to know that Perl uses different operators for comparing strings and numbers (see perlop for details). Note how I put the 9 in quotes so that the ne operator is comparing a string with a string (you were comparing a string with a number).

Finally, as a matter of style, you've used far too many comments. Your code seemed to get rather lost amongst them and, in this instance, I don't see any that actually add anything helpful.

Putting all that together, you might end up with something like:

use strict; use warnings; my $planet_count = "9"; while (1) { print "How many planets are there? "; chomp(my $planet_guess = <>); if ($planet_guess ne $planet_count) { print "Sorry that's not right, try again.\n"; next; } else { print "Well done! There are indeed $planet_count planets in th +e solar system.\n"; last; } }

Example output:

How many planets are there? 3 Sorry that's not right, try again. How many planets are there? 6 Sorry that's not right, try again. How many planets are there? 9 Well done! There are indeed 9 planets in the solar system.

P.S. I think Pluto got demoted to planetoid (or something), so there's only 8 planets now. :-)

-- Ken


In reply to Re: Help using a while loop with STDIN by kcott
in thread Help using a while loop with STDIN by amonline

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.