http://www.perlmonks.org?node_id=2461

vroom has asked for the wisdom of the Perl Monks concerning the following question: (arrays)

How can I find the union/difference/intersection of two arrays?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I find the union/difference/intersection of two arrays?
by chromatic (Archbishop) on Mar 29, 2000 at 01:07 UTC
    This version works. :)
    my @simpsons=("homer","bart","marge","maggie","lisa"); my @females=("lisa","marge","maggie","maude"); my %simpsons=map{$_ =>1} @simpsons; my %females=map{$_=>1} @females; # the intersection of @females and @simpsons: my @female_simpsons = grep( $simpsons{$_}, @females ); # proof it works print "Female Simpson:\t$_\n" foreach (@female_simpsons); # the difference of @females and @simpsons my @male_simpsons=grep(!defined $females{$_}, @simpsons); # proof it works print "Male Simpson:\t$_\n" foreach (@male_simpsons); my %union = (); # the union of @females and @simpsons foreach(@females,@simpsons){ $union{$_}=1; } my @union2 = keys %union; # or just do this # my @union = (@females, @simpsons);
Re: How can I find the union/difference/intersection of two arrays?
by DrHyde (Prior) on Jun 16, 2003 at 14:20 UTC
    TheDamian's Quantum::Superpositions module can do this. Although it is slow, the code is quite readable:
    use Quantum::Superpositions; my @a = (1,2,3,4,5,6,7,8,9,10); # integers my @b = (2,4,6,8,10,12,14,16,18,20); # doubled my @unionAB = sort { $a <=> $b } eigenstates( any(@a, @b) ); my @intersectionAB = sort { $a <=> $b } eigenstates( any(@a) == any(@b +) ); my @differenceAB = sort { $a <=> $b } eigenstates( any(@a) != all(@b +) );
Re: How can I find the union/difference/intersection of two arrays?
by McMahon (Chaplain) on May 27, 2004 at 22:03 UTC
    The List::Compare module has functions for all of these operations.
Re: How can I find the union/difference/intersection of two arrays?
by Dev Null (Acolyte) on Jun 07, 2017 at 15:56 UTC

    This is inefficient, but I use it for intersection when I know I'm guaranteed small list sizes, and it's more valuable / pleasing to me to have a one-line solution:

    my @isect = map { my $b = $_; grep { $_ eq $b } @a } @b;

      the problem with that method is that your @isect can contain identical elements

      for example,if @a=(1,2,3,4,2) and @b=(1,2,4), your @isect will be: (1,2,2,4)

      before using this method you have to make sure each element is unique in both tab