## DEV Community

Posted on • Updated on

# Random integer generation in an interval with Modern OOP Perl

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.

Tib

How are you doing the digital painting?

It's not computer generated through Perl unfortunately. I did it by hand, using Krita and a watercolor brush, plus adding more water on the "fresh" painting I guess. Actually I don't remember all the details very well and would maybe not be able to redo it again. Easier than real brushes and canvas that's all I know.

Tib

By hand = with a drawing tablet?

ðŸŒŒ SÃ©bastien FeugÃ¨re â˜” • Edited

Maybe but not sure because it is basically like trashing a bucket of painting on a canvas. It's more likely I did it on my ThinkPad trackpad or something.

The sources are here tknk.io/Aafd

Mark Gardner

I have to agree with your one-liner; writing a whole class for this seems a bit much.