Perl (Scripting) - Remove duplicate values from an array

by
Jeremy Canfield |
Updated: April 12 2022
| Perl (Scripting) articles
Let's say you have an array that has duplicate values.
@array = qw(one two one three one);
The following Perl script will remove the duplicates.
sub uniq {
my %seen;
grep not $seen{$_}++, @_;
}
@unique = uniq(@array);
Printing the @unique array will now produce the following.
one two three
Credit goes to Greg Hewgill at this Stack Overflow post.
Let's say you have a hash array that contains duplicate values.
push ( @{$hash{name}}, "Jeremy" );
push ( @{$hash{name}}, "Jeremy" );
The following will append the unique values to a new array (newhash).
my %seen;
my %newhash;
foreach my $key (keys %hash) {
foreach my $value (@{$hash{$key}}) {
if ( not $seen{$value}++) {
print "$value has not been seen yet\n";
push ( @{$newhash{name}}, "$value" );
}
else {
print "$value has been seen\n";
}
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at