Perl FAQ 5.4: How can I extract just the unique elements of an array?

Perl FAQ 5.4

How can I extract just the unique elements of an array?

There are several possible ways, depending on whether the array is ordered and you wish to preserve the ordering.

a) If @in is sorted, and you want @out to be sorted:

    $prev = 'nonesuch';
    @out = grep($_ ne $prev && (($prev) = $_), @in);

This is nice in that it doesn't use much extra memory, simulating uniq's behavior of removing only adjacent duplicates.

b) If you don't know whether @in is sorted:

    undef %saw;
    @out = grep(!$saw{$_}++, @in);

c) Like (b), but @in contains only small integers:

    @out = grep(!$saw[$_]++, @in);

d) A way to do (b) without any loops or greps:

    undef %saw;
    @saw{@in} = ();
    @out = sort keys %saw;  # remove sort if undesired

e) Like (d), but @in contains only small positive integers:

    undef @ary;
    @ary[@in] = @in;
    @out = sort @ary;


Other resources at this site: