[kw-pm] unique
John Macdonald
john at perlwolf.com
Wed Apr 19 08:06:55 PDT 2006
On Wed, Apr 19, 2006 at 05:22:50AM -0600, Dave Carr wrote:
> Found this snippet to do unique on a sorted array
>
>
>
> $prev = 'nonesuch';
>
> @uniq = grep($_ eq $prev && (($prev) = $_), @sorted);
>
>
>
> How could I modify this to require a string to occur at least two times
> to be included in the output array, in other words single occurrences
> will be skipped?
You've already noted that the 'eq' needs to be 'ne' for
that code to work.
$prev = 'nonesuch';
$count = 0;
$min_count = 2;
@multiples = grep {
$_ eq $prev
?? ( ++$count == $min_count )
:: ( ($prev = $_), ($count = 0) )
} @sorted;
That selects elements that have been seen exactly $min_count
times, so it skips elements that are not repeated that many
time, and only returns one copy of an element that occur
more times.
If you set $min_count to 1, it returns the unique elements as
before (but with a bit more processing overhead), if you set
it to a larger number, you can select a unique copy of every
element that occurs at least $min_count times.
--
More information about the kw-pm
mailing list