> Subject: Simple question
> Date: Fri, 8 Aug 2003 07:09:24 -0600
> From: "Trevor Morrison" <[EMAIL PROTECTED]>
> To: <[EMAIL PROTECTED]>
>
> Hi,
>
> I am trying to compare two arrays to find  common numbers in both.
For the
> numbers that are not common to both, I want to write them to a file
for my
> review.  I have included the code below, but it is not working as
intended.
> I know that this is a real basic question, but I have been staring at
this
> for hours and am not seeing it.  I am assuming that there must me a
module
> that will do this, but I have decided to reinvent the wheel!
>
> TIA
>
> Trevor


If you ever decide to get away from reinventing the wheel,
you might want to use some script from perlfaq4:


# This program compares 2 arrays and gives the Intersection (elements
# common to both arrays), Difference (elements that are in one of
# the arrays, but not both) and Union (all elements in either array).
#
# First, duplicates records are removed from both arrays.
# Then the Intersection, Difference, and Union are calculated
# and printed.
#
use strict;
use warnings;

my @in1 = ("a","b","c","d","e","f","g","d");
my @in2 = ("h","k","b",'c',"i","g","k","j");

# This strips duplicates out of @in1
#
undef my %saw1;
my @array1 = grep(!$saw1{$_}++, @in1);

# This strips duplicates out of @in2
#
undef my %saw2;
my @array2 = grep(!$saw2{$_}++, @in2);

# This is the Intersection, Difference, and Union part
#
my @union = my @intersection = my @difference = ();
    my %count = ();
    foreach my $element (@array1, @array2) { $count{$element}++ }
    foreach my $element (keys %count) {
        push @union, $element;
        push @{ $count{$element} > 1 ? [EMAIL PROTECTED] : [EMAIL PROTECTED] },
$element;
    }

print "\n\nIntersection: @intersection\n\n";
print "Difference: @difference\n\n";
print "Union: @union\n\n";

__END__



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to