http://qs321.pair.com?node_id=35134
Contributed by Anonymous Monk on Oct 03, 2000 at 20:25 UTC
Q&A  > Data Structures

#### Description:

Ahh how to kkep this simple- I need to generate 2+ hashes which I can then find intersection/difference between a master hash of set values. How can I carry out set theory with perl using hashes, or even arrays? For LARGE ammounts of key/value pairs?

 Answer: set theory w/hashes? arrays? done quickly?contributed by Fastolfe The Perl Cookbook has some excellent things to say on this topic, specifically in and about recipes 4.6 and 4.7. Hashes should be treated as an array of its keys when doing comparisons like this. In addition, see the Set::Scalar module, which is specifically designed to do manipulations and tests with sets. In a pinch, though, some code like this might help you (taken directly from the cookbook): ```foreach \$e (@a, @b) { \$union{\$e}++ && \$isect{\$e}++ } @union = keys %union; @isect = keys %isect; [download]``` If you need the difference: ```@diff = (); foreach \$e (keys %union) { push(@diff, \$e) unless \$isect{\$e}; } [download]``` Set::Scalar makes this much more straightforward: ```\$s = new Set::Scalar (keys %hash1); \$t = new Set::Scalar (keys %hash2); @isect = \$s->intersection(\$t)->members; [download]``` Answer: set theory w/hashes? arrays? done quickly?contributed by fundflow There has to be a better way using array slices...... got it Here is an example for union: ```%s1=('a'=>1, 'b'=>1, 'c'=>1); %s2=('a'=>1, 'c'=>1, 'd'=>1); print "Set 1 has: ", join(",",keys %s1), " Set 2 has: ", join(",", k +eys %s2),"\n"; %j=%s1; @j{keys %s2}=1; print "Union is ", join(",", keys %j), "\n"; [download]``` I don't really know how to remove elements from the hash. In the above example, the hash keys are the elements of the set. If you let the set be the elements in the hash that also have a nonzero value, then the same technique can be used for intersection: ```%inter=%s1; @inter{%s2}=0; [download]``` Also, to answer the original poster: if "REALLY large" is really large, and doesnt fit in the main memory then you might want to store the sets in sorted files and merge them smartly to compute the union/intersection. Answer: set theory w/hashes? arrays? done quickly?contributed by clemburg You want to read Mastering Algorithms with Perl. Chapter 6 is about Sets. It also discusses the following Set Modules from CPAN: Set::Scalar Set::Object Set::IntSpan Bit::Vector Set::IntRange