How do I store a duplicate value from an array or hash in Perl?
-
05-07-2019 - |
Question
Let's make this very easy. What I want:
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
How to print duplicate values of a array/hash?
Solution
sub duplicate {
my @args = @_;
my %items;
for my $element(@args) {
$items{$element}++;
}
return grep {$items{$_} > 1} keys %items;
}
OTHER TIPS
# assumes inputs can be hash keys
@a = (1, 2, 3, 3, 4, 4, 5);
# keep count for each unique input
%h = ();
map { $h{$_}++ } @a;
# duplicate inputs have count > 1
@dupes = grep { $h{$_} > 1 } keys %h;
# should print 3, 4
print join(", ", sort @dupes), "\n";
The extra verbose, extra readable version of what you want to do:
sub duplicate {
my %value_hash;
foreach my $val (@_) {
$value_hash{$val} +=1;
}
my @arr;
while (my ($val, $num) = each(%value_hash)) {
if ($num > 1) {
push(@arr, $val)
}
}
return @arr;
}
This can be shortened considerably, but I intentionally left it verbose so that you can follow along.
I didn't test it, though, so watch out for my typos.
Use a dictionary, put the value in the key, and the count in the value.
Ah, just noticed you've tagged as perl
while ([...]) { $hash{[dbvalue]}++ }
Unspecified in the question is the order in which the duplicates should be returned.
I can think of several possibilities: don't care; by order of first/second/last occurrence in the input list; sorted.
I'm going golfing!
sub duplicate {
my %count;
grep $count{$_}++, @_;
}
@array = qw/one two one/;
my @duplicates = duplicate(@array);
print "@duplicates"; # This should now print 'one'.
# or if returning *exactly* 1 occurrence of each duplicated item is important
sub duplicate {
my %count;
grep ++$count{$_} == 2, @_;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow