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

'uniq' Array

05.30.2005
| 26299 views |
  • submit to reddit
        A much more idiomatic and efficient version of the 'uniq array' code at <a href="http://www.bigbold.com/snippets/posts/show/152 ">152</a> is:

  # Input: @list
  # Output: @uniqed
  my %seen;
  my @uniqed = grep !$seen{$_}++, @list;

    

Comments

Snippets Manager replied on Fri, 2007/02/02 - 11:03pm

I should also point out that effeciency wise, they are about the same. pasang is just creating an anonymous hash, so I'm not sure what you in terms of speed or memory usage. Possibly its better because the anonymous hash goes away faster, but even the named hash will go away when the block closes.

Snippets Manager replied on Fri, 2007/02/02 - 11:03pm

The original version maintains order, and pasang_lhamu's solution does not.

Snippets Manager replied on Mon, 2012/05/07 - 2:12pm

There's nothing efficient in using an extra var. my @uniq = keys %{{ map { $_ => 1 } @list }};