Posted By

deepsoul on 09/14/09


list array hash-set

Versions (?)

Add array elements to hash set

 / Published in: Perl

Perl hash sets are hashes used to represent sets. Their keys are the set elements, and the corresponding values are just 1. For keys that are not set elements, the hash will return undef, equivalent to false.

Adding a whole array to a hash set is often useful, but how to do it is slightly tricky and not widely known. Here goes...

  1. my @ary= qw( foo bar bla ack 42 foo );
  3. my %set;
  4. @set{@ary}= (1) x @ary;
  5. # by the way: keys %set is now an array containing the elements
  6. # of @ary without duplicates! (though possibly shuffled)
  8. # or right during initialisation:
  9. my %set2= map { $_ => 1; } @ary;

Report this snippet  

You need to login to post a comment.