in reply to Help using a while loop with STDIN

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

Replies are listed 'Best First'.
Re^2: Help using a while loop with STDIN
by GrandFather (Saint) on Feb 07, 2012 at 23:18 UTC

    If you have a flow control statement (next, last, return, exit, ...) at the end of an if block, you don't need to follow the block with an else block which saves a level of indentation for the following code. I tend to call the technique "early exit". Be warned however that some purists frown on the technique claiming that "things should only have one exit point". I use the technique a lot because I think it tends to clean up code something wonderful.

    On a related note, if you change the sense of your if you don't need the next. For the resulting code see my earlier reply to the OP.

    Note that you have duplicated the OP's error in using ne in place of ==. On a related note you shouldn't quote the 9 in the assignment to $planet_count - a count is generally a number not a string after all.

    True laziness is hard work