develooper Front page | perl.perl5.porters | Postings from October 2000

[ID 20001027.007] uniq array in perlfaq

Thread Next
From:
Hans Ginzel
Date:
October 27, 2000 12:44
Subject:
[ID 20001027.007] uniq array in perlfaq
Message ID:
20001027192830.A1564@kolej.mff.cuni.cz
	Hello,

  there is in perlfaq:


=head1 Found in /usr/lib/perl5/5.005/pod/perlfaq4.pod

=head2 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.

=over 4

=item 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.


Why not to use

    $prev = 'nonesuch';
    @out = grep($_ ne $prev && ($prev = $_ or 1), @in);
 
to take out the disadvantidge?



Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About