🌌 Sébastien Feugère ☔
Posted on February 23, 2021
I always have to search how to generate a random integer number between a range because this is a common task that I use a lot in tests, but really, I can't memorize it.
Though, this is how I would do it in 2021.
use v5.16;
use strict;
use warnings;
# Class definition
package Random::Range {
use Zydeco;
class Integer {
method pick ( Int $min, Int $max ) {
return $min + int ( rand ( $max - $min ));
}
}
}
# Script
say Random::Range->new_integer->pick(1, 100);
#==> 42
So what did we do here? We used the rand
function where we applied the int
function, so we would get an integer, not a fractional number. The small calculation makes possible to restrict the result to the desired interval.
All of this is glued into a minimal Zydeco class that adds a very nice object-oriented interface. You maybe don't need Zydeco, this simple one-liner would work:
perl -le 'my @interval = (1, 100); print $interval[0] + int ( rand ( $interval[1] - $interval[0] ))'
Note this is not cryptographically secure and should only be used in simple cases: if you need a secure implementation, please check some appropriate solutions on CPAN.
Art: digital painting by myself.
Posted on February 23, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.