Dear monks,
recently I have found myself wanting to use sets, i.e. collections of unique values. I could use a CPAN package for it, but more often than not I simply write
my %set = (); my @new_items = ...; @set{@new_items} = (1) x @new_items;
Deleting items from the set is of course
delete @set{@other_items};
I don't know how common the idiom is. It may be inefficient with large sets and arrays, and the syntax is a bit peculiar for adding things to the set, but it saves conceptual effort and reduces running time compared to sorting and removing duplicate items later. You can also always reduce the set (hash) to an array with [keys %set].
Are there better ways to do it? Here, better can be any one of conceptually or syntactically clearer, less memory wasted in storing the items, or less memory wasted in adding items to the set.
A further advantage of the above idiom is that you can compute set difference and symmetric difference easily:
# Difference. sub difference { my %diff = %{ $_[0] }; delete @diff{ keys %{ $_[1] } }; \%diff; } # Symmetric difference. sub symmetric_difference { my %symm = (); my @set1 = keys %{ difference($_[0], $_[1]) }; my @set2 = keys %{ difference($_[1], $_[0]) }; @symm{@set1, @set2} = (1) x (@set1 + @set2); \%symm; }
An obvious problem with the idiom is auto-vivication, but as long as you're careful and consistent, it won't bite you.
--
print "Just Another Perl Adept\n";
In reply to Idiom: hashes as sets by vrk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |