标签:
以前写过类似的博客: http://blog.csdn.net/three_man/article/details/34084361
今天拿出来,再好好剖析一下:
my @arr1 = (1 .. 10);
my @arr2 = (5 .. 15);
# join multi array
my @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 -w
use strict;
use warnings;
use English;
my @arr1 = (1 .. 10);
my @arr2 = (5 .. 15);
# join multi array
my @arr = (@arr1, @arr2);
printArr(\@arr);
print "-------------------------------------\n";
my @uniqArr = removeRepeat(\@arr);
printArr(\@uniqArr);
# remove repeat element in array
sub removeRepeat
{
my $arrRef = shift;
my %count = ();
my @uniqArr = grep { ++$count{$_} == 1 } @$arrRef;
return @uniqArr;
}
# print array
sub printArr
{
my $arrRef = shift;
foreach my $element (@$arrRef)
{
print "$element\n";
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
Perl快捷删除数组重复元素,以前写过类似的博客,今天被问起时,却支支吾吾!
标签:
原文地址:http://blog.csdn.net/three_man/article/details/47138339