Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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

by faq_monk (Initiate)
on Oct 08, 1999 at 00:20 UTC ( #609=perlfaq nodetype: print w/replies, xml ) Need Help??

Current Perl documentation can be found at perldoc.perl.org.

Here is our local, out-dated (pre-5.6) version:

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

a) If @in is sorted, and you want @out to be sorted: (this assumes all true values in the array)

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

This is nice in that it doesn't use much extra memory, simulating uniq(1)'s behavior of removing only adjacent duplicates. It's less nice in that it won't work with false values like undef, 0, or ``''; ``0 but true'' is ok, though.

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 = @ary;

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[stevieb]: I'll see how to get in touch with someone and advise that there's an issue. Thanks for helping me confiirm pryrt!
[pryrt]: 5.14.2.1-32 also mismatches; but 5.24.1.1-64 matches their sha1
[pryrt]: The mismatched ones have a Jan 23 2017 Last-Modified header -- I wonder if they rezipped them and forgot to update the sha1
[stevieb]: RT ticket for the csum mismatch of various versions of Strawberry Perl

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (7)
As of 2017-03-29 21:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (353 votes). Check out past polls.