# initialize all sets to be empty @union = @intersection = @difference = (); %count = (); # count the number of times each unique element appears # in both arrays foreach $element (@array1, @array2) { $count{$element}++ } # for each unique element, determine whether it belongs # to the union, intersection, or difference of the original arrays foreach $element (keys %count) { # since the union includes all elements present in either # array, every unique element should belong to the union push @union, $element; # if this element occurred appeared more than once # (i.e., in both arrays), then it belongs to the intersection. # if it occurred only once (i.e., in only one array), then it # belongs to the difference. perlfaq4 explains that this is # -symmetric difference-, like an XOR operation. push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element; }