http://search.cpan.org/~pevans/Scalar-List-Utils-1.38/lib/List/Util.pm
http://search.cpan.org/~adamk/List-MoreUtils-0.33/lib/List/MoreUtils.pm
一, Util
use List::Util qw(first max maxstr min minstr reduce shuffle sum);By default
List::Util
does not export any subroutines.
#!/usr/bin/perl -w use List::Util qw(first max maxstr min minstr reduce shuffle sum); my @array = qw(12 23 34 45 56 67); print("shuffle = "); print (sum @array); print("\n"); print("max = "); print (max @array); print("\n"); print("min = "); print (min @array); print("\n"); print("fisrt = "); print (fisrt @array); print("\n"); print("shuffle = "); print (shuffle @array); print("\n");
结果:
zl@zl-vm:~/study/perl/list$ perl list.pl
Unquoted string "fisrt" may clash with future reserved word at list.pl line 20.
Name "main::fisrt" used only once: possible typo at list.pl line 20.
shuffle = 237
max = 67
min = 12
print() on unopened filehandle fisrt at list.pl line 20.
fisrt =
shuffle = 672334561245
zl@zl-vm:~/study/perl/list$
注意 : fisrt出错,处理方法:first函数必须这样使用。
print("fisrt = "); my $my_first = first {defined ($_)} @array; print $my_first; #print (fisrt {defined($_)} @array); print("\n");
参考
Similar to grep
in that it evaluates BLOCK
setting $_
to each element of @list
in turn. first
returns the first element where the result from BLOCK
is a true value. If BLOCK
never returns true or @list
was empty then undef
is returned.
$foo = first { defined($_) } @list # first defined value in @list $foo = first { $_ > $value } @list # first value in @list which # is greater than $value
二,MoreUtil
use List::MoreUtils qw{ any all none notall true false firstidx first_index lastidx last_index insert_after insert_after_string apply indexes after after_incl before before_incl firstval first_value lastval last_value each_array each_arrayref pairwise natatime mesh zip uniq distinct minmax part };
总结:MoreUtil是Util的升级版,你需要什么,就qw什么,就可以帮你实现相应的功能。
uniq的使用方法:
Returns a new list by stripping duplicate values in LIST. The order of elements in the returned list is the same as in LIST. In scalar context, returns the number of unique elements in LIST.
my @uniq_array = uniq 1,1,2,2,3,2,1,2; print ("@uniq_array"."\n"); my $uniq_x = uniq 1,2,3,4,5; print ($uniq_x."\n"); my $uniq_y = uniq 5,4,3,2,1; print ($uniq_y."\n");
zl@zl-vm:~/study/perl/list$ perl list.pl
1 2 3
5
5
zl@zl-vm:~/study/perl/list$
总结:
my $uniq_x = uniq 1,2,3,4,5;
my $uniq_y = uniq 5,4,3,2,1;
这两个表达式输出的结果是一样的。说明uniq函数在遇到多个uniq的数时会先排序,选择最大的。