Home > Software engineering >  How we take just two numbers in Perl using rand?
How we take just two numbers in Perl using rand?

Time:05-21

In Perl using rand can we exclude number between max and min except some number.

Max 3 Min 1

X = Int (rand(max - min 1) min )

Result will be 1 and 2 and 3

I want to except 2 how did it in Perl?

CodePudding user response:

Simple, extensible approach:

my @nums = grep { $_ != $exclude } $min..$max;
my $n = int( rand( @nums ) );

Avoids building an array:

my $n = int( rand( $max - $min ) );
$n  = $min;
  $n if $n >= $exclude;

For picking between two values:

my $n = rand() >= 0.5 ? $min : $max;

CodePudding user response:

If I understood correctly from comments, you want to select randomly from two possible values, right?

You can do it using a ternary operator like this:

$x = rand > 0.5 ? $min : $max;

In your particular example it can be:

$x = rand > 0.5 ? 1 : 3;
  • Related