Home > Software engineering >  How to remove duplicate reference in array?
How to remove duplicate reference in array?

Time:10-13

Consider this array:

my @array = (hashref1, hashref2, hashref3, hashref1);

How can I remove the duplicate reference hashref1.

CodePudding user response:

If by "duplicate reference" you mean they both refer to the same anonymous hash, you can use List::Util's uniq:

#!/usr/bin/perl
use warnings;
use strict;

use List::Util qw{ uniq };
use Data::Dumper;

my $hashref1 = {a => 10};
my $hashref2 = {b => 11};
my $hashref3 = {c => 12};

my @array = ($hashref1, $hashref2, $hashref3, $hashref1);

print Dumper(uniq(@array));

Output:

```perl
$VAR1 = {
          'a' => 10
        };
$VAR2 = {
          'b' => 11
        };
$VAR3 = {
          'c' => 12
        };

The stringified versions of the references will be used for comparison, i.e. something like HASH(0x560ee5fdf220). The same references have the same address.

But, if you mean they refer to different objects with the same contents, you need to find a way how to stringify the hashrefs so that the contents is always the same.

#!/usr/bin/perl
use warnings;
use strict;

use List::Util qw{ uniq };
use Data::Dumper;

my $hashref1 = {a => 10, A => 2};
my $hashref2 = {b => 11, B => 3};
my $hashref3 = {c => 12, C => 4};
my $hashref4 = {a => 10, A => 2};

my @array = ($hashref1, $hashref2, $hashref3, $hashref4);

my @serialized = do {
    # Comment out the following line to see how 1 and 4
    # can be different sometimes.
    local $Data::Dumper::Sortkeys = 1;
    map Dumper($_), @array;
};
my $VAR1;
print Dumper(map eval, uniq(@serialized));
  •  Tags:  
  • perl
  • Related