我需要知道如何在perl中随机填充数组。例如:我想声明一个包含10个小于60的元素的数组。有人可以解释一下我该怎么做或给我发送任何指南?我会非常感激。
答案 0 :(得分:5)
我假设你的意思是“十个非负整数小于60”。
有可能重复:
my @rands = map { int(rand(60)) } 1..10;
例如,
$ perl -E'say join ",", map { int(rand(60)) } 1..10;'
0,28,6,49,26,19,56,32,56,16 <-- 56 is repeated
$ perl -E'say join ",", map { int(rand(60)) } 1..10;'
15,57,50,16,51,58,46,7,17,53
$ perl -E'say join ",", map { int(rand(60)) } 1..10;'
13,57,26,47,30,14,47,55,39,39 <-- 47 and 39 are repeated
没有重复的可能性:
use List::Util qw( shuffle );
my @rands = (shuffle 0..59)[0..9];
例如,
$ perl -MList::Util=shuffle -E'say join ",", (shuffle 0..59)[0..9];'
13,50,8,21,11,24,28,51,55,38
$ perl -MList::Util=shuffle -E'say join ",", (shuffle 0..59)[0..9];'
1,0,58,46,47,49,52,33,5,13
$ perl -MList::Util=shuffle -E'say join ",", (shuffle 0..59)[0..9];'
19,43,45,49,23,53,2,38,59,35
答案 1 :(得分:2)
您可以这样做:
my @r = map int(rand(60)), 0..9;
say Dumper\@r;
答案 2 :(得分:-1)
您可以利用perl对哈希键的随机排序。每次运行时,这将随机填充10个元素的数组:
use warnings;
use strict;
my @nums = (1 .. 60);
my %data;
$data{$_}++ foreach @nums;
my $count = 0;
my @random;
foreach (keys %data){
$count++;
push @random, $_ if $count <= 10;
}