標籤:
以前寫過類似的部落格: http://blog.csdn.net/three_man/article/details/34084361
今天拿出來,再好好剖析一下:
1. 構造一個含有重複元素的數組
my @arr1 = (1 .. 10);my @arr2 = (5 .. 15);# join multi arraymy @arr = (@arr1, @arr2);
2. 刪除數組中的重複元素
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"; }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Perl快捷刪除數組重複元素,以前寫過類似的部落格,今天被問起時,卻支支吾吾!