Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

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}
  • Comment on create a array which is XOR of two arrays

Replies are listed 'Best First'.
Re: create a array which is XOR of two arrays
by Corion (Patriarch) on Oct 23, 2006 at 07:02 UTC
Re: create a array which is XOR of two arrays
by BrowserUk (Patriarch) on Oct 23, 2006 at 08:35 UTC

    What you've shown does not exactly match your description. An XOR (symmetric difference) operation (per the FAQ) would leave @final = ( t3, t5, t7, t8 );. Ie. Those elements that appear only in one or the other array but not both.

    To achieve what you've shown (and described except for the XOR reference), you could do

    C:\test>p1 @array1 = qw[ t1 t2 t3 ];; @array2 = qw[ t1 t2 t5 t7 t8 ];; @seen{ @array1 }=(); @final = grep !exists $seen{ $_ }, @array2;; print "@final";; t5 t7 t8

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: create a array which is XOR of two arrays
by Anonymous Monk on Oct 23, 2006 at 10:23 UTC
    @final = do {my %t; @t{@array2} = (); delete @t{@array1}; keys %t;};