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

In reply to Re: Comparing each element of Array A to Array B by eric256
in thread Comparing each element of Array A to Array B by lali

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.