in reply to Comparing each element of Array A to Array B

Lots of ways to do it, loops, grep, hashes, etc. If you want all the elements in A that arn't B then you can use grep. Grep will return a list of elements matching a criteria. So you mix two grep statments together, the inner most will check if a given element $a is in array @b, the outer grep will go over @a, setting each element to $a and then running the inner test. If the inner test is true then we include the element. I reversed the inner test with a ! to make it show the ones NOT in @B, removing the ! would make it print only those matching elements.

I then did the same with for and grep, and then finaly with two for loops. Hopefully this will help you see how the original solution works and how much easier it is ;)

#!/usr/bin/perl use strict; use warnings; my @a = (1,2,3,4,5); my @b = (1,3,4); print "Using Grep:"; my @c = grep { $a = $_; !grep { $_ eq $a } @b } @a; print join(",", @c), "\n"; print "Using For and Grep:\n"; for $a (@a) { print $a,"\n" if !grep { $a eq $_ } @b; } print "Using only For:\n"; for $a (@a) { my $found = 0; for $b (@b) { $found = 1 if $a eq $b; } print $a,"\n" if !$found; }

___________
Eric Hodges

Replies are listed 'Best First'.
Re^2: Comparing each element of Array A to Array B
by ikegami (Patriarch) on Aug 09, 2007 at 17:41 UTC
    The difference between your solutions and those previously posted is speed. Yours is O(N*N), whereas those previously posted are a much faster O(N).

      True, but the example data was small and some times its more important to do it in a way that makes sense than the fastest way. I know when i started hashes where confusing concepts since they barely exist in other language, true they are now one of my favorites, but if you are new and someone solves an array problem with a hash solution it can be confusing.


      ___________
      Eric Hodges
Re^2: Comparing each element of Array A to Array B
by lali (Initiate) on Aug 09, 2007 at 19:16 UTC
    Thanks Eric! PerlMonks is really great! Iam starting to learn Perl. Any suggestions...

      Yep, PerlMonks :-D. Take a look through the Tutorials section, and if you have any questions, you know where to ask.

      It's also worth looking at the Seekers of Perl Wisdom section. Many of the questions posted there will be obscure or way beyond your present knowledge, but many will introduce bits of Perl and ways of using it that don't leap off the pages of a text book. Be prepared to do some digging in the Perl documentation (see perlintro for a start then perltoc).


      DWIM is Perl's answer to Gödel