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

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to