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?
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?
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 ==
.
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) ...
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";
}