📘 ‘Guess the number’ in Perl 6

Write a program that generates a random integer number 0 through 10 and asks the user to guess it, saying if the entered value is too small or too big.

First, a random number needs to be generated. In Perl 6, the randroutine can be called on an integer object, and it returns a random floating-point value between 0 and that integer. As the task requires a random integer number, call the roundmethod on the result:

10.rand.round

Now, ask for the initial guess and enter the loop, which compares the guess with $n.

my $n = 10.rand.round;

my $guess = prompt('Guess my number between 0 and 10: ');

while $guess != $n {
    if $guess < $n {
        say 'Too small.';
    }
    elsif $guess > $n {
        say 'Too big.';
    }
    $guess = prompt('Try again: ');
}

say 'Yes, this is it!';

The ifelsif chain may be replaced with a ternary operator:

say $guess < $n ?? 'Too small.' !! 'Too big.';

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s