CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Frequently Asked Questions:
How can I extract just the unique elements of an a

 



Jasmine
Administrator

Jan 19, 2001, 3:06 PM

Post #1 of 1 (2946 views)
How can I extract just the unique elements of an a Can't Post

(From the Perl FAQ)

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

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)

Code
    $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:

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

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

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

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

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

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

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


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives