17

I need to add unique elements in an array from inputs which contain several duplicate values.

How do I avoid pushing duplicate values into an Perl array?

2
  • you can use the notion of a set: stackoverflow.com/questions/3700037/… Commented Apr 9, 2013 at 6:31
  • There is always List::MoreUtils uniq function if you are not opposed to the CPAN. Commented Apr 9, 2013 at 6:41

3 Answers 3

22
push(@yourarray, $yourvalue) unless grep{$_ == $yourvalue} @yourarray;

This checks if the value is present in the array before pushing. If the value is not present it will be pushed.

If the value is not numeric you should use eq instead of ==.

Sign up to request clarification or add additional context in comments.

2 Comments

This solution becomes very inefficient as the array grows large--the hash method is to be preferred.
Above Answer is right, but it does not work if $_ is used in above/below statement, like chomp($_) while reading from a file. The following: " push(@yourarray, $yourvalue) unless $yourvalue ~~ @yourarray; " works perfectly.
21

You simply need to use hash like this:

my %hash;
$hash{$key} = $value;  # you can use 1 as $value
...

This will automatically overwrite duplicate keys.

When you need to print it, simply use:

foreach my $key (keys %hash) {
    # do something with $key
}

If you need to sort keys, use

foreach my $key (sort keys %hash) ...

1 Comment

Wow, this must be new record: answer accepted 4 years later :)
3

by using ~~ we can minimum perl version is 5.10.1

use v5.10.1;
use strict;
use warnings;

my @ARRAY1 = qw/This is array of backup /;
my @ARRAY2;
my $value = "version.xml";

sub CheckPush($$) {
    my $val = shift (@_);
    my $array_ref = shift (@_);

    unless ($val ~~ @$array_ref) {
        print "$val is going to push to array\n";
        push(@$array_ref, $val);
    }

    return (@$array_ref);
} 

@ARRAY1 = CheckPush($value, \@ARRAY1);
print "out\n";

foreach (@ARRAY1) {
    print "$_\n";
}

@ARRAY2 = CheckPush ($value, \@ARRAY2);
print "out2\n";

foreach (@ARRAY2) {
    print "$_\n";
}

2 Comments

In short: push(@yourarray, $yourvalue) unless $yourvalue ~~ @yourarray;
Note that smart match was downgraded to experimental since it often acted contrary to what people expected, and had other issues.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.