First off, always use strictures (use strict; use warnings;). If you had perl would have told you that there are only 8 planets (well, maybe not - it may have told you there are 767 known planets).

Rewriting your code using strictures, a while loop and making a couple of fixes (and cleaning out the comments) we get:

#!/usr/bin/perl use strict; use warnings; my $kSolarPlanets = 8; print "How many planets are there? "; while (defined(my $planets = <>)) { chomp $planets; if ($planets == $kSolarPlanets) { print "Well done there are indeed $kSolarPlanets planets in th +e solar system"; last; } print "Sorry that's not right, try again: "; }

Note the use of == for the numeric equality check instead of eq which performs a string equality check. 8 == 8.0 is true but 8 eq 8.0 is false.

Please don't clutter your code with comments that describe the exciting new language features you have just learned. They don't help the compiler and they don't help you. They do make it almost impossible to actually see the code!

Don't put multiple statements on one line (I'm looking at you else line) because the statements after the first tend to disappear.

Actually the real reason to use strictures is to pick up a range of trivial to make errors (like typos) that can lead to really hard to find bugs. Strict won't actually check that your planets constant is the correct number :(.

True laziness is hard work

In reply to Re: Help using a while loop with STDIN by GrandFather
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.