in reply to Re^2: Finding unique elements in an array
in thread Finding unique elements in an array

But that's not what uniq does: it only removes elements that are the same as the previous element in the list.
Are you looking at a different version of perlfaq4? My perl 5.8.6 version of perlfaq 4 "How can I remove duplicate elements from a list or array" gives 5 options, option a) of which states:
If @in is sorted, and you want @out to be sorted: (this assumes all true values in the array)
$prev = "not equal to $in[0]"; @out = grep($_ ne $prev && ($prev = $_, 1), @in);
This is nice in that it doesn't use much extra memory, simulating uniq(1)'s behavior of removing only adjacent duplicates. The ``, 1'' guarantees that the expression is true (so that grep picks it up) even if the $_ is 0, ``'', or undef.

Replies are listed 'Best First'.
Re^4: Finding unique elements in an array
by Roy Johnson (Monsignor) on Mar 15, 2005 at 15:12 UTC
    I thought it looked like a nice job for List::Util, but it requires too much fiddling to make it come up with an array, so it's not really elegant. (The reason I wanted to try it is that it pre-loads $prev.)
    use List::Util 'reduce'; sub uniq { return @{;reduce {ref $a or $a=[$a]; push @$a, $b if $b ne $a->[-1 +]; $a} @_}; };
    So it looks like grep is the right tool.

    Update: This is a little shorter version with grep:

    sub uniq { return @_ ? @_[0, grep {$_[$_] ne $_[$_-1]} 1..$#_] : (); };

    Caution: Contents may have been coded under pressure.
Re^4: Finding unique elements in an array
by Joost (Canon) on Mar 15, 2005 at 13:35 UTC