Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Application using random

We have a simple application that uses the rand function to generate a random number between 0 and 1 (0 included, 1 not) and then it return an integer between 1 and n (both included).

package MyRandomApp;
use strict;
use warnings;

use Exporter qw(import);
our @EXPORT_OK = qw(dice);

sub dice {
    my ($n) = @_;
    my $rnd = rand();
    # print "dice: $rnd\n";
    return 1 + int($rnd * $n);
}

1;

This is a script using it.

use strict;
use warnings;
use feature 'say';

use MyRandomApp qw(dice);

say dice(6);
say dice(6);
say dice(6);

$ perl -Ilib bin/dice.pl
1
3
6