in reply to union, intersection, and difference
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 }).# 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; }
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 :-)
|
|---|