Over a million developers have joined DZone.

Efficient 'uniq' Snippet

DZone's Guide to

Efficient 'uniq' Snippet

· ·
Free Resource
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;


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}