#!/usr/bin/perl -w use strict; # this initialization to () is not necesssary, but ok my (@union, @intersection, @difference, %count) = (); my @array1 = (1,2,3); my @array2 = (3,4,1); foreach my $element (@array1, @array2) { $count{$element}++; #auto-vivification of a hash entry } foreach my $element (keys %count) # a print to show results so far { print "$element occured $count{$element} times\n"; } @union = keys %count; # same as the push @union, $element statement # it would be faster to have this within the # foreach loop, because calculating the keys # takes some "work", but I'm showing here # what this does. @union and keys %count are # equivalent. foreach my $element (keys %count) { if ($count{$element} > 1) #element occured more than once { push @intersection, $element; } else #element only occured once { push @difference, $element; } } print "union=@union; intersection=@intersection; difference=@difference\n"; __END__ 4 occured 1 times 1 occured 2 times 3 occured 2 times 2 occured 1 times union=4 1 3 2; intersection=1 3; difference=4 2