in reply to Help with While Loop
Unfortunately, putting the curly braces in doesn't make the code work. The user's input must be repeated in the loop, too, otherwise the code would test the same number again and again.
#! /usr/bin/perl use warnings; use strict; my $im_thinking = int rand 10; print "Pick a number: "; my $guess = -1; while ($guess != $im_thinking) { $guess = <STDIN>; chomp $guess; if ($guess > $im_thinking) { print "You guessed too high!\n"; } elsif ($guess < $im_thinking) { print "You guessed too low!\n"; } } print "You got it right!\n";
Update: You can use last and the ternary operator to make the code even simpler:
#! /usr/bin/perl use warnings; use strict; my $im_thinking = int rand 10; print "Pick a number: "; while () { my $guess = <STDIN>; chomp $guess; last if $guess == $im_thinking; print "You guessed too ", $guess < $im_thinking ? 'low' : 'high', "\nTry again: "; } print "You got it right!\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: OT: Pythonesque C
by AnomalousMonk (Archbishop) on Sep 14, 2015 at 19:15 UTC | |
|
Re^2: Help with While Loop
by gavin100 (Initiate) on Sep 14, 2015 at 12:46 UTC |