View Single Post
Old 09-22-2004, 10:26 PM  
irishfury
Confirmed User
 
Join Date: Aug 2003
Location: In the hearts of cowards
Posts: 2,611
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;
__________________
Trust no one there all snakes
irishfury is offline   Share thread on Digg Share thread on Twitter Share thread on Reddit Share thread on Facebook Reply With Quote