问题
I have multiple values for each key in the hash. Here, I print the values of each key
print "$var:",join ',',@{$hash{$var}},"\n";
Output of the above print statement is:
ABC:1,2,3,1,4,2,
DEF:9,3,4,5,3,5,
Now, I want to remove duplicates in the values. The desired output is,
ABC:1,2,3,4
DEF:9,3,4,5
Can someone help me in this?
Thanks
回答1:
Personally, I like how List::MoreUtils's uniq handles this. The subroutine is quite simple, and can be used as-is, or through the module.
my %seen;
my @dedupe = grep { not $seen{$_}++ } @{$hash{$var}};
The subroutine from the module looks like this:
sub uniq (@) {
my %seen = ();
grep { not $seen{$_}++ } @_;
}
This code preserves the initial order of the list.
回答2:
Using List::MoreUtils::uniq:
@$_ = uniq @$_ foreach values %hash;
回答3:
That it's in a hash is irrelevant. What you're wanting to do is dedupe the values in an array.
Look at the uniq()
function in List::MoreUtils module http://search.cpan.org/dist/List-MoreUtils/
You can also do it yourself like so:
my %h = map {($_,1)} @array_with_dupes;
my @deduped_array = keys %h;
This is all covered extensively in the Perl FAQ under "Data: Arrays".
回答4:
If you are trying to remove duplicate values from an array you can use this
#!/usr/bin/perl -w
use strict;
my @array = ('a','b','c','c','e');
my %hash = map { $_ => 1 } @array;
my @out = keys %hash;
printf("%s",join(',',@out));
来源:https://stackoverflow.com/questions/12921151/how-do-i-remove-duplicate-values-from-an-array-in-perl