in reply to What is the best way to get just the duplicates from an array?

Use a hash to count each occurrance and then grep to get those that appear more than once.

my @a = qw/ 1 2 3 4 5 6 7 8 9 5 7 9 /; my %h; $h{$_}++ for @a; my @dups = grep { $h{$_} > 1 } keys %h; print "@dups\n";

Is one way.

  • Comment on Re: What is the best way to get just the duplicates from an array?
  • Download Code

Replies are listed 'Best First'.
Re^2: What is the best way to get just the duplicates from an array?
by ikegami (Patriarch) on Jul 27, 2007 at 15:03 UTC
    Combining your loops into one:
    my @a = qw/ 1 2 3 4 5 6 7 8 9 5 7 9 5 /; my %seen; my @dups = grep ++$seen{$_}==2, @a; print "@dups\n";
      That's damned sneaky. I like it++