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

Is there any one liner to extract the duplicates alone from an array.

Replies are listed 'Best First'.
Re: Extract Duplicates by one liner
by hardburn (Abbot) on Mar 04, 2005 at 15:23 UTC
    my @array = qw( foo bar bar baz ); my %h; $h{$_}++ for @array; my @dup = grep $h{$_} > 1, keys %h; print join( ", ", @dup );

    "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: Extract Duplicates by one liner
by Anonymous Monk on Mar 04, 2005 at 15:20 UTC
    Extract, as in "gimme the duplicates"? It's a FAQ, but here's an answer anyway:
    my @dups = do {my %h; grep $h{$_}++, @array};

      That doesn't seem to work:

      $ perl -le 'my @array = qw( foo bar bar baz); my @dups = do {my %h; gr +ep $h{$_}++, @array}; print join( ", ", @dup );' $

      Update: Nevermind. That'll teach me to use strict.

      Prints nothing.

      "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: Extract Duplicates by one liner
by RazorbladeBidet (Friar) on Mar 04, 2005 at 15:52 UTC
    How about:

    print $_, "\n" foreach grep { $_ if $hash{$_}++; } @list

    (fluff has been excluded)
    --------------
    It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
      grep returns a list of values for which the code block is true. You're returning $_ if it's a duplicate, which means you'll never return duplicated false values (that is, if @list = (0, 0, "", "", "0", "0", undef, undef) you'll get nothing out of it).
      Getting golfy over here, but you don't even need the $_ if part:

      @a=qw/foo bar bar baz/; print join ", ", grep { !$h{$_}++ } @a;

A reply falls below the community's threshold of quality. You may see it by logging in.