SPUG: create a array which is XOR of two arrays

Chris Cantrall chris_cantrall at yahoo.com
Mon Oct 23 14:51:50 PDT 2006

Quoting the FAQ:

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;

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.




----- Original Message ----
From: Sachin Chaturvedi <sachin_chat at coolgoose.com>
To: spug-list at pm.org
Sent: Monday, October 23, 2006 12:41:23 AM
Subject: SPUG: create a array which is XOR of two arrays

i have two arrays
@array1 = { t1, t2 , t3 }
@array2 = ( t1 , t2 , t5, t7, t8}
i want to create a new array which has all elements of array2 such that they
are not in array1.
i mean my final array should be
@final = {t5,t7,t8}
Seattle Perl Users Group Mailing List  
     POST TO: spug-list at pm.org
SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
    MEETINGS: 3rd Tuesdays
    WEB PAGE: http://seattleperl.org/

More information about the spug-list mailing list