Here is the code with some of my own comments. Hopefully it is helpful.
# initialize all sets to be empty @union = @intersection = @difference = (); %count = (); # count the number of times each unique element appears # in both arrays foreach $element (@array1, @array2) { $count{$element}++ } # for each unique element, determine whether it belongs # to the union, intersection, or difference of the original arrays foreach $element (keys %count) { # since the union includes all elements present in either # array, every unique element should belong to the union push @union, $element; # if this element occurred appeared more than once # (i.e., in both arrays), then it belongs to the intersection. # if it occurred only once (i.e., in only one array), then it # belongs to the difference. perlfaq4 explains that this is # -symmetric difference-, like an XOR operation. push @{ $count{$element} > 1 ? \@intersection : \@difference }, $e +lement; }
The ternary ?: operator is a shorthand for if/then/else, and is explained further in perlop. The last statement works because push requires an array, which we get by dereferencing a reference to an array (like this: @{ \@array }).

It seems to me, though, that this code only works if the elements of each array are unique. If the same element appears twice in one array, it will become part of the intersection set, although it shouldn't. (Update: If I had read perlfaq4 carefully myself, I would have seen that this assumption is documented. oops :-)


In reply to Re: union, intersection, and difference by thelenm
in thread union, intersection, and difference by trowa

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.