#!/usr/bin/perl -w # returns union, intersection and differences of two arrays # as per sections 14.7 and 14.8 of the Perl Cookbook # (but does not preserve order!) # usage: # ( \@merged, \@common, \@only_a, \@only_b ) = intersets(\@a, \@b) sub intersets { my ($a, $b) = @_; my (%ah, %bh); @ah{ @$a } = @$a; @bh{ @$b } = (); delete @bh{ @$a }; ( [ keys %ah, keys %bh ], [ grep defined, delete @ah{ @$b } ], [ keys %ah ], [ keys %bh ] ) } my @a = qw(a b c d e); my @b = qw(b e f g h i); print "[ @a ], [ @b ]\n "; my($mrg, $common, $a, $b) = intersets(\@a, \@b); print "merged: '@$mrg'\ncommon: '@$common'\n"; print "only a: '@$a'\nonly b: '@$b'\n"; =pod [ a b c d e ], [ b e f g h i ] merged: 'a b c d e h i f g' common: 'b e' only a: 'a c d' only b: 'h i f g' =cut