Re: Simple loop question
- From: lawrence@xxxxxxxxx (Lawrence Statton)
- Date: Wed, 31 May 2006 09:41:40 -0700
Hi list,
Hope this is not too simple or a stupid question:
I have a slight problem with a loop. It is a simple numbers guessing game. It
works fine, but when I run this script, it gives me "Too low" immediately aft
er
the prompt. What should I do to get the last "else" statement displayed first
?
Nothing. You should re-arrange your code to do the tests you want in
the order you want them.
Get in the habit of using strict and warnings -- 'use warnings' is
subtly different from 'perl -w' and you should start good habits
early. Upgrade if you are using an ancient version of Perl that does
not come with warnings.
I would also advise getting in the habit of tidying up things you get
from STDIN. While "3\n" is just as three as "3", were you to start
using $guess in a print (e.g. print "$guess was too low\n"; ) you'd
have some ugly output.
#!/usr/bin/perl
use strict;
use warnings;
our ($upper, $lower, $target) = ( 20, 1, 11 );
while (1) {
chomp (my $guess = <STDIN>);
if ($guess < $lower or $guess > $upper) {
print "Try a guess that is between $lower and $upper\n";
} elsif ($guess < $target) {
print "Too low\n";
} elsif ($guess > $target ) {
print "Too high\n";
} elsif ($guess == $target) {
print "You got it!\n";
last;
}
}
.
- Follow-Ups:
- Re: Simple loop question
- From: Danny
- Re: Simple loop question
- From: Lawrence Statton
- Re: Simple loop question
- References:
- Simple loop question
- From: Danny
- Simple loop question
- Prev by Date: CPAN Install Problem
- Next by Date: Re: Simple loop question
- Previous by thread: Re: Simple loop question
- Next by thread: Re: Simple loop question
- Index(es):
Relevant Pages
|