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; }
|
|---|
| 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 | |
by eric256 (Parson) on Aug 09, 2007 at 20:58 UTC | |
|
Re^2: Comparing each element of Array A to Array B
by lali (Initiate) on Aug 09, 2007 at 19:16 UTC | |
by GrandFather (Saint) on Aug 09, 2007 at 20:56 UTC |