in reply to finding union, intersection and differences of arrays

my @a = qw(a b c d e f); my @b = qw(c d e f g h); my ($only_a, $only_b, $both, $either) = listy(\@a, \@b); print "only in a: @$only_a\n"; print "only in b: @$only_b\n"; print "both: @$both\n"; print "either: @$either\n"; sub listy { my %tmp1; for (0..1) { for my $k (@{$_[$_]}) { $tmp1{$k} .= $_; } } my %tmp2; while (my($k, $v) = each %tmp1) { push @{$tmp2{$v}}, $k; } return @tmp2{"0", "1", "01"}, [keys %tmp1]; }

-- Randal L. Schwartz, Perl hacker

Replies are listed 'Best First'.
Re: •Re: finding union, intersection and differences of arrays
by Jasper (Chaplain) on Mar 28, 2002 at 18:06 UTC
    I seem to have nothing better to do, but in case you have more than two arrays..
    my ($only_a, $only_b, $only_c, $all, $any) = listy(\@a, \@b, \@c); sub listy { my %tmp1; my @keys; for (0..$#_) { my $key = pop @keys; push @keys, $_, (defined $key ? $key : '') . $_; for my $k (@{$_[$_]}) { $tmp1{$k} .= $_; } } my %tmp2; while (my($k, $v) = each %tmp1) { push @{$tmp2{$v}}, $k; } return @tmp2{@keys}, [keys %tmp1]; }
    (maybe I should have tested it better the first time. Fixed bug) Jasp