本文共 1058 字,大约阅读时间需要 3 分钟。
以前写过类似的博客:
今天拿出来,再好好剖析一下:my @arr1 = (1 .. 10);my @arr2 = (5 .. 15);# join multi arraymy @arr = (@arr1, @arr2);
sub removeRepeat{ my $arrRef = shift; my %count = (); my @uniqArr = grep { ++$count{ $_} == 1 } @$arrRef; return @uniqArr;}
定义一个计数哈希,并且初始化为空,即:my %count = ();
该哈希%count的key为数组元素(即:上面代码中的$_),value为数组重复元素的计数(即:上面代码中的$count{$_}, 初始化值为0,并且该哈希通过key每获取一次value, value都会++)代码块{ ++$count{$_} == 1 }作为无重复元素的判断条件,并通过grep得到一个满足无重复元素的子数组
完整代码:
#!/usr/bin/perl -wuse strict;use warnings;use English;my @arr1 = (1 .. 10);my @arr2 = (5 .. 15);# join multi arraymy @arr = (@arr1, @arr2);printArr(\@arr);print "-------------------------------------\n";my @uniqArr = removeRepeat(\@arr);printArr(\@uniqArr);# remove repeat element in arraysub removeRepeat{ my $arrRef = shift; my %count = (); my @uniqArr = grep { ++$count{ $_} == 1 } @$arrRef; return @uniqArr;}# print arraysub printArr{ my $arrRef = shift; foreach my $element (@$arrRef) { print "$element\n"; }}
转载地址:http://hhqya.baihongyu.com/