Re: Simple loop question



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



Relevant Pages

  • Re: debugger exiting
    ... strict and warnings pragmas. ... I think portraying Perl as a command-line tool limits it to fewer platforms than ... work only as a Unix shell command line. ...
    (perl.beginners)
  • Re: dns querry script.
    ... use warnings; ... use strict; ... C:\Dload> perl dns.pl ...
    (comp.lang.perl.misc)
  • Re: Any way to access global variable in Perl script from one module file?
    ... use strict; ... use warnings; ... a separate process has a completely separate memory space. ... There is probably no reason to create a new perl ...
    (comp.lang.perl.misc)
  • Re: Debug Help Please
    ... In Perl there is the expression TIMTOWTDI which means that you will probably get different opinions on "The Right Way" to do something in Perl. ... use strict; ... That is a specious argument because you can disable specific strictures or warnings in local scope: ... for all Failures ...
    (perl.beginners)
  • Re: Align Text
    ... On Dec 21, 2003, at 10:47 PM, Bill Jastram wrote: ... use strict; ... use warnings; ... These promise Perl you'll play by the good programmer rules, ...
    (perl.beginners)