Skip to content

Instantly share code, notes, and snippets.

@xenoterracide
Created April 25, 2010 22:11
Show Gist options
  • Save xenoterracide/378768 to your computer and use it in GitHub Desktop.
Save xenoterracide/378768 to your computer and use it in GitHub Desktop.
Guess a Number Game
#!/usr/bin/env perl
# guess a number game
use strict;
use warnings;
use feature qw( say state switch );
say 'welcome';
# generate the winning number between 1 and 10
# see perlfaq4 for algorithm details
my $winning_num = 1 + int( rand( (10-1)+1 ) );
until ( $winning_num
== ( state $guess = 0 )
) {
say 'Guess a number between 1 and 10: ';
$guess = readline(*STDIN);
# check to see if we have a winner, or the guess is to high, or low.
given( $guess ) {
# sanitize input
# this must be first otherwise it won't work right
when ( $_ !~ /[[:digit:]]/ ) {
say 'not a number';
# set $guess to 0 so we don't have a numerical comparison warning
$guess = 0;
}
when ( $_ > $winning_num ) {
say 'Too high';
}
when ( $_ < $winning_num ) {
say 'Too low';
}
when ( $winning_num ) {
say 'You Win!';
}
}
}
say 'Game over!';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment