Jun 22, 2008

Find difference, union and intersection of two arrays

#!F:\Perl\bin\perl -w

use Data::Dumper;
@union = @intersection = @difference = ();
%count = ();

#Make sure that both arrays are unique
my @array1 = (10, 20, 30, 40, 50, 60);
my @array2 = (50, 60, 70, 80, 90, 100);

foreach $element (@array1, @array2) { $count{$element}++ }

#print "\n all values hash:", Dumper(\%count);

foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}


print "\n Union values:", Dumper(\@union);
print "\n Intersection Values:", Dumper(\@intersection);
print "\n Difference Array:", Dumper(\@difference);
print "\n";

No comments:

Post a Comment