I'm completely replacing this answer. The old answer gave a lot
of clever answers and used special cases rather than emphasizing 
the trick: use a hash.

Although I show the idiomatic map(), I also through in the more
newbie-friendly foreach.



=head2 How can I remove duplicate elements from a list or array?

(contributed by brian d foy)

Use a hash. When you think the words "unique" or "duplicated",
think "hash keys".

If you don't care about the order of the elements, you could 
just create the hash then extract the keys. It's not important
how you create that hash: just that you use C<keys> to get the
unique elements.

   my %hash   = map { $_, 1 } @array;
   # or a hash slice: @hash{ @array } = ();
   # or a foreach: $hash{$_} foreach ( @array );

   my @unique = keys %hash;

You can also go through each element and skip the ones you've
seen before. Use a hash to keep track. The first time the loop
sees an element, that element has no key in C<%Seen>. The
C<next> statement creates the key and immediately uses its
value, which is C<undef>, so the loop continues to the C<push>
and increments the value for that key. The next time the loop
sees that same element, its key exists in the hash I<and> the
value for that key is true (since it's not 0 or undef), so 
the next skips that iteration and the loop goes to the next
element.

   my @unique = ();
   my %Seen   = ();
    foreach my $elem ( @array )
      {
      next if $Seen{ $elem }++;
      push @unique, $elem;
      }

You can write this more briefly using a grep, which does the
same thing.

   my %Seen = ();
   my @unique = grep { ! $Seen{ $elem }++ } @array;

-- 
brian d foy, [EMAIL PROTECTED]

Reply via email to