Perl Idioms Explained - keys %{{map{$_=>1}@list}}

my @list = qw/a b c d d a e b a b d e f/; my @uniq = keys %{{ map {$_ => 1} @list }}; print "@list\n@uniq\n"; __output__ a b c d d a e b a b d e f e f a b c d
The above idiom is a simple way of creating a list of unique values from another list, as the output of the code aptly demonstrates. However, with all those curly braces it may not be immediately obvious what's going on, so let's break it down.
map { $_ => 1 } @list
This is pretty straight-forward - create a list of key-value pairs where the keys are the values from @list.
{ map { $_ => 1 } @list }
The surrounding pair of curly braces creates an anonymous hash which is populated with they key-value pairs from the map statement. So we now have a hash reference to an anonymous hash who's keys are the elements from @list, and because hash keys are unique, the keys of the anonymous hash represent a unique set of values.
keys %{ { map { $_ => 1 } @list } }
Finally, with the last pair of curly braces the hash reference to the anonymous hash is dereferenced and we get its list of keys.


Because this idiom creates a list, and then a hash, both of which are immediately disposed of, it's not suited for large lists. Also, because the keys of a hash aren't ordered, the list of unique values returned will be in a random order (although this can often be remedied with a simple sort).


A short (memory hungry) way to get a list of unique values from a given list.