# 7个perl数组高级操作技巧分享

2017-09-04 11:50:30来源:CSDN作者:mjj_1094人点击

# 7个perl数组高级操作技巧分享

1、去除一个数组中的重复元素：

my @array = ( 'a', 'b', 'c', 'a', 'd', 1, 2, 5, 1, 5 );
my %count;
my @uniq_times = grep { ++\$count{ \$_ } < 2; } @array;

my @array = ( 'a', 'b', 'c', 'a', 'd', 1, 2, 5, 1, 5 );
my %saw;
@saw{ @array } = ( );
my @uniq_array = sort keys %saw;

2、合并两个array:

push @array1, @array2;

3、快速查找最大值，不知道的程序猿们，这样搞：

my @nums = 0 .. 1000;
my \$max = \$nums[0];
foreach (@nums) {
\$max = \$_ if \$_ > \$max;
}

use List::Util qw(max);
my \$max_num = max( 0 .. 1000 );

use List::Util qw(maxstr);
my \$max_str = maxstr ( qw( Fido Spot Rover ) );

use List::Util qw(sum);
my \$sum = sum ( 1 .. 1000 );

4、列表归并

use List::Util qw(reduce);
my \$sum = reduce { \$a + \$b } 1 .. 1000;

my \$product = reduce { \$a * \$b } 1 .. 1000;

5、判断是否有元素匹配

my \$found_a_match = grep { \$_ > 1000 } @list;

my \$found_a_match = 0;
foreach my \$elem (@list) {
\$found_a_match = \$elem if \$elem > 1000;
last if \$found_a_match;
}

use List::Util qw(first);
my \$found_a_match = fist { \$_ > 1000 } @list;

my \$found_a_match = any { \$_ > 1000 } @list;
my \$all_greater = all { \$_ > 1000 } @list;
my \$none_greater = none { \$_ > 1000 } @list;
my \$all_greater = notall { \$_ % 2 } @list;

6、一次遍历多个列表

my @a = ( ... );
my @b = ( ... );
my @c;

foreach my \$i ( 0 .. \$#list ) {
my ( \$a, \$b ) = ( \$a[\$i], \$b[\$i] );
push @c, \$a + \$b;
}

use List::MoreUtils qw(pairwise);
my @c = pairwise { \$a + \$b } @a, @b;

pairwise只适合两个列表的同步计算，三个后用each_array：

use List::MoreUtils qw(each_array);

my \$ea = each_array( @a, @b, @c );

my @d;
while ( my ( \$a, \$b, \$c ) = \$ea->() ) {
push @d, \$a+\$b+\$c;
}

7、数组合并

use List::MoreUtils qw(mesh);

my @odds = qw/ 1 3 5 7 9/;
my @evens= qw/ 2 4 6 8 0/;

my @nums = mesh @odds, @evens; # print： 1 2 3 4 ...