我有一个从平面文件中读取的数组,如下所示:
@Array = ('01026¦Cummington¦Massachusetts¦MA',
'01026¦West Cummington¦Massachusetts¦MA',
'01030¦East Hampton¦Massachusetts¦MA',
'01027¦Easthampton¦Massachusetts¦MA',
'01027¦Loudville¦Massachusetts¦MA',
'01030¦Mount Tom¦Massachusetts¦MA',
'01027¦Westhampton¦Massachusetts¦MA',
'01028¦East Longmeadow¦Massachusetts¦MA',
'01029¦Big Pond¦Massachusetts¦MA');
我想要做的是获得@Array [1]的三个随机“数值”,所以我得到一个如下所示的输出:
print "01028
01026
01030";
答案 0 :(得分:6)
如果我理解正确,则可以使用List::Util
的shuffle
函数轻松实现:
#!/usr/bin/env perl
use strict;
use warnings;
use List::Util qw( shuffle );
my @array = (
'01026¦Cummington¦Massachusetts¦MA',
'01026¦West Cummington¦Massachusetts¦MA',
'01030¦East Hampton¦Massachusetts¦MA',
'01027¦Easthampton¦Massachusetts¦MA',
'01027¦Loudville¦Massachusetts¦MA',
'01030¦Mount Tom¦Massachusetts¦MA',
'01027¦Westhampton¦Massachusetts¦MA',
'01028¦East Longmeadow¦Massachusetts¦MA',
'01029¦Big Pond¦Massachusetts¦MA',
);
my @shuffled_array = ( shuffle 0 .. @array - 1 )[ 0 .. 2 ];
print join "\n", map $array[$_] =~ /^(\d+)/, @shuffled_array;