SPUG: create a array which is XOR of two arrays

Trey Harris trey+spug at lopsa.org
Wed Oct 25 09:27:15 PDT 2006


In a message dated Tue, 24 Oct 2006, Creede Lambard writes:
> John W. Krahn wrote:
>> Creede Lambard wrote:
>>
>>> The quick and dirty version:
>>>
>>> #!/usr/bin/perl
>>>
>>> @array1 = ( t1, t2 , t3 );
>>> @array2 = ( t1 , t2 , t5, t7, t8);
>>>
>>> my %hash = ();
>>> foreach $element (@array2) { $hash{$element} = 1; }
>>> foreach $element (@array1) { delete $hash{$element}; }
>>>
>>> @final = keys %hash;
>>>
>>> Someone is going to chew me out, and rightly so, for not using strict
>>> and -w.
>>>
>>
>> Or you could do it without the loops:
>>
>> my %hash;
>> @hash{ @array2 } = ();
>> delete @hash{ @array1 };
>>
>> @final = keys %hash;

Either way, it should be noted that you're not preserving the original 
order of @array2 if you use C<keys>.  The OP's email did give the final 
list in order, but did not say whether that was coincidental.

If you want ordering preserved though,

   my %hash;
   @hash{@array1} = ();
   my @final = grep { ! exists $hash{$_} } @array2;
   print "@final\n";

would work.

Trey


More information about the spug-list mailing list