DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Efficient 'uniq' Snippet

04.12.2005
| 9503 views |
  • submit to reddit
        This snippet will quickly uniq an unsorted array; in other words, remove duplicates.   (note: for large arrays, it may be more efficient to sort the array first and simply keep track of consecutive dups instead of using a hash.)

  # Input: @list
  # Output: @uniqed
  my %u = ();
  @uniqed = grep {defined} map {
      if (exists $u{$_}) { undef; } else { $u{$_}=undef;$_; }
    } @list;
  undef %u;