Learning Perl here.. So I wrote this number guessing script but can't see
what is wrong with it. I can never get the solution even when I know it's
correct. What am I doing wrong?
Looks like you already got some good answers. Let me add a few minor comments...
#!/usr/bin/env perl
use Math::Random; use strict;
You should add a:
use warnings;
I believe this would have even caught your previous mistake.
sub run(){
Don't declare subroutines like that. Use:
sub run { # no parens
my $solution = random_uniform_integer(1, 1, 100); my $guess = undef; do { print "\$solution = $solution\n"; print "Guess (1 - 100) ?\n"; chomp(my $guess = <STDIN>); if ($guess > $solution) { print "$guess is too HIGH!\n"; } if ($guess < $solution) {
The above should probably be:
elsif ($guess < $solution) {
print "$guess is too LOW!\n"; } } while ($guess != $solution); print "$guess is correct, YAY!\n";
Move the rest of this subroutine outside, into the general script (around your run(); call). There's no need to use recursion for this.
James
print "Play again? "; chomp(my $answer = <STDIN>); if (lc($answer) eq 'y') { run(); } }
run();
TIA :)
-- Greg Donald [EMAIL PROTECTED]
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>