関数順 インデックス
目的別 インデックス

構文
 
 rand 乱数の範囲

返り値
 
 指定した範囲の乱数

説明

  • 指定した範囲にある乱数を返します。
  • 引数を省略すると0以上1未満の乱数を返します。

使用例

0以上10未満の乱数を取得する
#!/usr/bin/perl
use strict;
use warnings;

my $rnd = rand 10;
print $rnd, "\n";
0以上100未満の乱数を整数で取得する
#!/usr/bin/perl
use strict;
use warnings;

foreach (1..20) {
  my $rnd = int rand 100;
  print $rnd, "\n";
}
0以上100未満の乱数を整数で取得する(毎回同じ系列)
#!/usr/bin/perl
use strict;
use warnings;

srand 1;
foreach (1..20) {
  my $rnd = int rand 100;
  print $rnd, "\n";
}
0以上100未満の乱数を整数で取得する(メルセンヌ・ツイスタ法)
#!/usr/bin/perl
use strict;
use warnings;
use Math::Random::MT qw/rand/;

foreach (1..20) {
  my $rnd = int rand 100;
  print $rnd, "\n";
}
※高品質の乱数が必要な場合はMath::Random::MTモジュールを使います。