in reply to tweaking of perldoc function (sorting/preserving order)

my @array1 = (1,2,3,4,5); my @array2 = (4,5,6,7,8); my %counts; my @union = grep ++$counts{$_} == 1, @array1, @array2; my @intersection = grep $counts{$_} == 2, @array1; my @difference = grep $counts{$_} == 1, @array1; my @intersection_c = grep $counts{$_} == 1, @array1, @array2; print "Union: @union\n"; print "Intersection: @intersection\n"; print "Difference: @difference\n"; print "Complement of intersection: @intersection_c\n";
Union: 1 2 3 4 5 6 7 8 Intersection: 4 5 Difference: 1 2 3 Complement of intersection: 1 2 3 6 7 8

Note that your code (and almut's) incorrectly calculates the difference.

Replies are listed 'Best First'.
Re^2: tweaking of perldoc function (sorting/preserving order)
by lodin (Hermit) on Jan 18, 2008 at 08:42 UTC

    ikegami:

    Note that your code (and almut's) incorrectly calculates the difference.

    perlfaq4 (from where the code is taken):

    Note that this is the symmetric difference, that is, all elements in either A or in B but not in both. Think of it as an xor operation.

    That means that what ikegami calls "complement of intersection" is was perlfaq4 calls "(symmetric) difference". Different authors have different definitions for difference and the symbol they use, such as - or \.

    perlfaq4 is correct with the definition of difference it provides.

    lodin