1、去除一个数组中的重复元素:
使用grep函数代码片段:
代码:
my @array = ( 'a', 'b', 'c', 'a', 'd', 1, 2, 5, 1, 5 ); my %count; my @uniq_times = grep { ++$count{ $_ } < 2; } @array;
使用转换hash代码片段:
代码:
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、列表归并
数字求和,也可以用List::Util中的reduce:
use List::Util qw(reduce); my $sum = reduce { $a + $b } 1 .. 1000;
好了,可以这样了:
my $product = reduce { $a * $b } 1 .. 1000;
5、判断是否有元素匹配
纯粹用Perl实现,找到列表中第一个符合某条件的元素,比找出所有符合条件的要麻烦一些。下面的例子,判断是否有大于1000的元素:
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;
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、数组合并
合并多个数组的操作当然你可以自己写,但终究不如MoreUtils的mesh方便:
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 ...