I've written a similar blog before: http://blog.csdn.net/three_man/article/details/34084361
Take it out today and take a good look at it:
1. Construct an array containing duplicate elements
my @arr1 = (1 .. 10);
my @arr2 = (5 .. 15);
# join multi array
my @arr = (@arr1, @arr2);
2. Delete duplicate elements in the array
sub removeRepeat
{
my $arrRef = shift;
my %count = ();
my @uniqArr = grep { ++$count{$_} == 1 } @$arrRef;
return @uniqArr;
}
-
Defines a count hash and initializes it to NULL, which is: my%count = ();
The hash%count key is an array element (that is, $_ in the code above), and value is a count of the number of repeating elements of the array (that is, $count{$_} in the code above, with an initialization value of 0, And the hash is obtained by key each time value, value will + +)
-
The code block {+ +$count{$_} = = 1} is used as a criterion for non-repeating elements, and a subarray that satisfies the non-repeating element is obtained by grep
Full code:
#!/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";
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Perl shortcut to delete array repeating elements, previously wrote a similar blog, today asked, but the shuffle!