kumar kumar -4 years ago 91
Perl Question

comparison of two arrays and finding the missing elements and from which array in perl

I have two arrays i need to find out what elements are present in both the arrays and what elements are missing and from which array?
I am using the below code to find the common elements in both the arrays and list of missing elements from both arrays can anyone tell me how can i find the list of elements missing from each array.'

for ex: from below code i need to print element "ghi" missing from @arr2 and element "mno" missing from @arr1

@arr1=("abc","def","ghi","jkl");
@arr2=("mno","abc","jkl","def");

my %count = ();
foreach $element (@arr1,@arr2){
$count{$element}++;
}
my @diff = grep { $count{$_} == 1 } keys %count;
my @common = grep { $count{$_} == 2 } keys %count;

Answer Source

If you put the items of @arr1 and @arr2 also in hashes, you could do:

my @miss1 = grep { $count{$_} == 1 && !exists $arr1{$_} } keys %count;
my @miss2 = grep { $count{$_} == 1 && !exists $arr2{$_} } keys %count;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download