Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

How do I pick anything that is in array A that is NOT in array B

Originally posted as a Categorized Question.

  • Comment on How do I pick anything that is in array A that is NOT in array B

Replies are listed 'Best First'.
Re: How do I pick anything that is in array A that is NOT in array B
by Anonymous Monk on Jun 30, 2000 at 12:20 UTC
Re: How do I pick anything that is in array A that is NOT in array B
by gansi (Initiate) on Jan 27, 2010 at 09:51 UTC
    use strict; my @A = (2..5); my @B = (4..7); my @A_not_B; foreach my $data ( @A ) { push @A_not_B, $data unless grep { $_ eq $data } @B; } print "FINAL :: @A_not_B \n";

      This is O(N*M) (where N is sizeof A, and M is sizeof B). You can do it in O(N+M) by building a hash with the contents of B, and using that for your test (instead of grep).

      my %B = map { $_ => 1 } @B; foreach my $data ( @A ) { push @A_not_B, $data unless $B{$data}; }

      You could also replace the foreach loop with:

      @A_not_B = grep { ! $B{$_} } @A;

      If N and M are large, the difference between O(N+M) and O(N*M) can be substantial. For the sample set, it is probably not noticeable.

      It is said that "only perl can parse Perl." I don't even come close until my 3rd cup of coffee. --MidLifeXis