Add array elements to hash set


/ Published in: Perl
Save to your folder(s)

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...


Copy this code and paste it in your HTML
  1. my @ary= qw( foo bar bla ack 42 foo );
  2.  
  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)
  7.  
  8. # or right during initialisation:
  9. my %set2= map { $_ => 1; } @ary;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.