Here's one way to accomplish what you want, and it eliminates some of
the redundancy.  BTW, get used to using strict.  It really does help in
the long run and it's better to learn it early than to decide to go back
later and fix your old programs.

###################################

#!/usr/bin/perl -w
use strict;

my $upper = 20 ;
my $lower = 1 ;
my $target = 11 ;
my $guess;

until(defined $guess)
  {
      print "Please choose a number between $lower and $upper\n" ;
      $guess = <STDIN> ;    

   if ( $guess > $target )
      {
        print "Too high\n" ;
        $guess = undef;
      }
    elsif ( $guess < $target )
      {
        print "Too low\n" ;
        $guess = undef;
      }
    elsif ( $guess == $target )
      {
        print "You guessed right\n" ;
        exit ;
      }
  }

#######################################

-----Original Message-----
From: Danny [mailto:[EMAIL PROTECTED] 
Sent: Wednesday, May 31, 2006 8:59 AM
To: Perl-beginners
Subject: 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 after
the prompt. What should I do to get the last "else" statement displayed
first?

Following is the code:

#!/usr/bin/perl -w

$upper = 20 ;
$lower = 1 ;
$target = 11 ;

while ( )
  {
    if ( $guess > $target )
      {
        print "Too high\n" ;
        $guess = <STDIN> ;
      }
    elsif ( $guess < $target )
      {
        print "Too low\n" ;
        $guess = <STDIN> ;
      }
    elsif ( $guess == $target )
      {
        print "You guessed right\n" ;
        exit ;
      }
    else
      {
        print "Please choose a number between ${lower} and ${upper}\n" ;
        $guess = <STDIN> ;
      }
    }



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