Multiple ways to remove duplicate elements from an array in Perl with code example
This tutorial explains multiple ways to remove duplicate elements in Perl Array.
How to get Unique elements from an array in Perl
To remove elements from an array in Perl, Please follow the below steps.
Use List::MoreUtils uniq function
The List::MoreUtils module provides a uniq function to filter duplicate elements and return unique elements from an array.
import
uniqfrom theList::MoreUtilslibrary
call the
uniqmethod with an array of duplicate valuesReturns array by removing duplicate values Here is an example
use List::MoreUtils qw(uniq);
my @numbers = (1,2,3,1,1,4,3,2);
my @result = uniq(@numbers);
print "@numbers\n";
Output:
1 2 3 4
Use subroutine with grep syntax
- Create a subroutine to check duplicate values and filter them. The advantage of a subroutine is to call multiple times with variable arguments.
- Inside a subroutine, call
grepwith expression to filter duplicate values - Finally, return
uniquearray elements.
my @numbers = (1,2,3,1,1,4,3,2);
sub unique {
my %array;
grep !$array{$_}++, @_;
}
my @result = unique(@numbers);
print "@result\n";
Convert to hash and return Keys
This approach, Convert an array into a hash object with keys as array numbers and values and Finally, returns keys Since Hash does not allow duplicate values as a key.
- Convert to Hash using the
mapfunction. map { $\_ => 1 } @numberscode iterates each element and converts it to a hash object, it ignores the duplicate elements.- return keys of a hash using
keys.
Here is an example
my @numbers = (1,2,3,1,1,4,3,2);
my %hashVariable = map { $\_ => 1 } @numbers;
my @result = keys %hashVariable;
print "@result";
To summarize, Shown multiple approaches, choose based on your needs and coding style.
