Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to compare arrays and find what differs?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Hi,
I'm comparing two arrays like:
#put them on one row
$object1=join("",@object1);
$object2=join("",@object2);
#remove all spaces, tabs, newlines etc
$object1 =~ s/\s+//g;
$object2 =~ s/\s+//g;
#compare them
if($object1 ne $object2)
{
print "This differs ???\n";
}

This compares them but I also want to know what's not equal.
How can I find out which parts that don't match?
brgds
Andreas
 
Perhaps a bit convoluted but this seems to work;

#!/usr/bin/perl -w

use strict;

my @arr1 = (1,2,3,4,5,6,7);
my @arr2 = (3,4,5,6,7,8,9,10);
my %hash;
my $to_be_cmpd;
my @difs;

if(scalar(@arr1) > scalar(@arr2)) {

map{$hash{$_} = ""} @arr1;
$to_be_cmpd = \@arr2;
}else{
map{$hash{$_} = ""} @arr2;
$to_be_cmpd = \@arr1;
}

for my $key (keys(%hash)) {

for my $val (@$to_be_cmpd) {

if($val eq $key) {

$hash{$key} = $val;

}

}

}

for (keys(%hash)) {

if($hash{$_} eq "") {

push(@difs, $_);

}
}

map{print $_ . "\n"} @difs;


greadey
 
Sorry Misled you,

It doesn't quite work right but I think there is enough to get to what you want, even if you have to do it twice.

greadey
 
You could try this ....

# @array1 -First array
# @array2 -Second array

%temp=();

@temp{@array1}=();

foreach $member (@array2)
{
delete $temp{$member};
}

@parts_that_dont_match=sort keys(%temp);


regards
C

"Brahmaiva satyam"
-Adi Shankara (788-820 AD)
 
Sorry about my first offering it doesn't work as I expected, and to get all the diffs from both arrays is quite involved. This does work though (and it's simpler);

#!/usr/bin/perl -w

use strict;

my @arr1 = (1,2,3,4,5);
my @arr2 = (3,4,5,6,7);
my $i;
my $j;


for($i=0; $i <= $#arr1; $i++) {

for($j=0; $j <= $#arr2; $j++) {

if($arr2[$j] =~ /$arr1[$i]/) {

$arr2[$j] = $arr1[$i] = &quot;Matched&quot;;
}

}

}

map { print $_ . &quot;\n&quot; if $_ !~ /Matched/} @arr1;

map { print $_ . &quot;\n&quot; if $_ !~ /Matched/} @arr2;



 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top