Unique Arrays

in Data Structures, Perl Tips
by William Ward on July 21, 2002 4:37 pm

If you have an array that may contain the same value in several places, and you would like to sort the array and remove all duplicates, here’s one way to do it…

First, make a hash using the elements of the array as keys. It doesn’t matter what the values are. For example:

  my %hash = map { $_ => 1 } @array;

The "map" function converts each array element into a tuple consisting of that value and 1. The results are then loaded into the hash as key/value pairs. The key is the array element and the corresponding value in the hash is 1. Even if two or more array elements have the same value, each key will only be in the hash once, because hash keys must be unique.

Then we take that hash and sort the keys:

  my @array2 = sort keys %hash;

And voila! Now you have all the elements of the original array, sorted, and each value occuring only once!

1 Comment »

  1. Thank you.

    Comment by Ronnie — July 17, 2008 @ 5:58 am

RSS feed for comments on this post. TrackBack URI

Leave a comment