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 uniq from the List::MoreUtils librar

    y

  • call the uniq method with an array of duplicate values

  • Returns 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 grep with expression to filter duplicate values
  • Finally, return unique array 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 map function.
  • map { $\_ => 1 } @numbers code 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.