
KevinR
Veteran

Oct 5, 2004, 11:07 PM
Post #8 of 12
(2318 views)
|
Re: [d1zz13] Looping through two arrays
[In reply to]
|
Can't Post
|
|
From Perldocs faqs: How do I compute the difference of two arrays? How do I compute the intersection of two arrays? Use a hash. Here's code to do both and more. It assumes that each element is unique in a given array:
@union = @intersection = @difference = (); %count = (); foreach $element (@array1, @array2) { $count{$element}++ } foreach $element (keys %count) { push @union, $element; push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element; } Note that this is the symmetric difference, that is, all elements in either A or in B but not in both. Think of it as an xor operation. ---------------------------------- substitue your arrays and give it a try.
#!/usr/bin/perl # File location my $flocation = '/home/domains/dizzie.co.uk/user/htdocs/compare/scompare'; print "Content-type: text/html\n\n"; # Open the new list of assets to compare open (NEW, "<$flocation/new.txt") || die "Unable to open new.txt\n $!\n"; @new = <NEW>; close NEW; # Open the existing list of assets to compare against open (EXISTING, "<$flocation/existing.txt") || die "Unable to open existing.txt\n $!\n"; @existing = <EXISTING>; close EXISTING; @union = @intersection = @difference = (); %count = (); foreach $element (@new, @existing) { $count{$element}++ } foreach $element (keys %count) { push @union, $element; push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element; } print "Intersection:<br>\n"; print "$_<br>\n" for @intersection; print "<br>Difference:<br>\n"; print "$_<br>\n" for @difference; -------------------------------------------------
|