wenD has asked for the wisdom of the Perl Monks concerning the following question:

This node falls below the community's minimum standard of quality and will not be displayed.
  • Comment on What is the best way to get just the duplicates from an array?

Replies are listed 'Best First'.
Re: What is the best way to get just the duplicates from an array?
by Corion (Patriarch) on Jul 27, 2007 at 15:07 UTC

      Thanks! The perlfaq4 example (with the ! for unique removed) is the one that I'll use from now on.

      my %seen = (); my @duplicates = grep { $seen{ $_ }++ } @array;
        That won't work. If there's three of the same thing, it will print the duplicate twice. That's why I used == in my earlier post instead of (an implied) >.
Re: What is the best way to get just the duplicates from an array?
by FunkyMonk (Bishop) on Jul 27, 2007 at 14:56 UTC
    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.

      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++
Re: What is the best way to get just the duplicates from an array?
by injunjoel (Priest) on Jul 27, 2007 at 16:44 UTC
    Another shameless plug? possibly... but apropos.
    Great suggestions thus far, so in the spirit of TIMTOWTDI I would suggest having a look at
    The Uniqueness of hashes.
    It's a collection of some techniques for just this sort of operation.

    -InjunJoel
    "I do not feel obliged to believe that the same God who endowed us with sense, reason and intellect has intended us to forego their use." -Galileo