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 remove duplicate elements from an array in Perl

To remove elements from an array in Perl, Please follow the below steps.

using List MoreUtils uniq function

  • import uniq from the List::MoreUtils librar


  • 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";


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 returns Keys

This approach, Convert an array into a hash object with keys as array numbers and values and Finally, return keys Since Hash does not allow duplicate values as a key.

  • Convert to Hash using the map function
  • 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";