How do I store a duplicate value from an array or hash in Perl?


How do I store a duplicate value from an array or hash in Perl?



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?




Replacing multiple occurrences in nested arrays

1:



Comparing generic list to an array
sub duplicate {     my @args = @_;     my %items;     for my $element(@args) {         $items{$element}++;     }     return grep {$items{$_} > 1} keys %items; } 


How do I remove objects from an array in Java?


what is `int *userMask[3][4]` pointing to?

2:



MATLAB class array
# 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"; 


Reverse Method for an Array of int


Remove empty elements from an array in Javascript

3:



What is best way to implement variable length arrays?
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..


4:


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]}++ } 


5:


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..


6:


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, @_; }



88 out of 100 based on 48 user ratings 598 reviews