Hello Greg,

> Thanks for you comments.  Is this the best way then?  Seems to work, but
I'm 
> curious what could be any better..

Your version is fine. Here's mine, just so you have another take on how to
do some things. Among a few other things, I added checking for so that the
guess has to be a number between 1 and 100 (this was not checked in your
version, so when you did $guess > $solution, the script would give an error
if the person entered a letter, for example).

#!/usr/bin/perl -w
#use Math::Random;
use strict;
use warnings;

my $play = 1;
while ($play) {
    print "\nI'm thinking of a number between 1 and 100.\n";
    print "Try and guess which number it is, and you might win
something!\n";

    # I don't have Math::Random. Uncomment the line below and the 'use' line
    # above, and comment the next one if you have it and want to use it.
    #my $solution = random_uniform_integer(1, 1, 100);
    my $solution = int(rand(100)) + 1;
    my $guess = undef;
    my $tries = 0;
    while (!$guess || $guess != $solution) {

        #print "\$solution = $solution\n";
        print "Guess ? (1-100): ";
        chomp($guess = <STDIN>);
        if ($guess =~ /^\d+$/ && $guess >= 1 && $guess <= 100) {
            if ($guess > $solution) {
                print "$guess is too HIGH!\n";
            }
            elsif ($guess < $solution) {
                print "$guess is too LOW!\n";
            }
        }
        else {
            print "Guess is not valid!\n";
        }

        $tries++;
    }

    my $try_word = ($tries == 1 ? 'try' : 'tries');
    print "$guess is correct, YAY! It only took you $tries $try_word!\n";
    print "You win $tries more minutes of free time!\n";
    print "Play again? (y/n): ";
    chomp(my $answer = <STDIN>);
    if ($answer !~ /^y/i) {
        $play = 0;
    }
}


That's it... Good luck with your Perl programming!

J-S

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