<?xml version="1.0" encoding="windows-1252"?>
<node id="611" title="How do I compute the difference of two arrays? How do I compute the intersection of two arrays?" created="1999-10-07 20:20:52" updated="2005-08-09 06:23:05">
<type id="834">
perlfaq nodetype</type>
<author id="519">
faq_monk</author>
<data>
<field name="doctext">

&lt;P&gt;
Use a hash. Here's code to do both and more. It assumes that each element
is unique in a given array:

&lt;P&gt;
&lt;PRE&gt;    @union = @intersection = @difference = ();
    %count = ();
    foreach $element (@array1, @array2) { $count{$element}++ }
    foreach $element (keys %count) {
        push @union, $element;
        push @{ $count{$element} &amp;gt; 1 ? \@intersection : \@difference }, $element;
    }
&lt;/PRE&gt;
&lt;P&gt;
</field>
</data>
</node>
