|Problems? Is your data what you think it is?|
Idiom: hashes as setsby w-ber (Hermit)
|on Jul 02, 2008 at 18:21 UTC||Need Help??|
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
Deleting items from the set is of course
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:
An obvious problem with the idiom is auto-vivication, but as long as you're careful and consistent, it won't bite you.