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

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?



Answers

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


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.

By : ysth


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.

By : SquareCog


This video can help you solving your question :)
By: admin