If you just want the intersection of the two arrays and all values are unique within each array, something like this should work:
#!/usr/bin/perl -w use strict; my @array1 = qw[a b c d e]; my @array2 = qw[a n o t h e r]; my %count; foreach my $element (@array1, @array2) { $count{$element} += 1; } foreach my $key (keys %count) { print "$key appears in both arrays\n" if $count{$key} == 2; }
Output:
$ ./foo.pl a appears in both arrays e appears in both arrays
For something a little more complex (but also more robust, more flexible, and probably faster) you could do this:
#!/usr/bin/perl -w use strict; my @array1 = qw[a b c d e]; my @array2 = qw[t e s t d a t a]; my @sort1 = sort @array1; my @sort2 = sort @array2; while (@sort1 && @sort2) { if ($sort1[0] eq $sort2[0]) { my $match = $sort1[0]; while (@sort1 && $sort1[0] eq $match) { shift @sort1; } while (@sort2 && $sort2[0] eq $match) { shift @sort2; } print "$match is in both arrays\n"; } elsif ($sort1[0] lt $sort2[0]) { shift @sort1; } else { shift @sort2; } }
which produces
$ ./bar.pl a is in both arrays d is in both arrays e is in both arrays
without getting a false positive on 't' like the first version would.

In reply to Re: any smart ideas??:) by dsheroh
in thread Comparing two arrays (was: any smart ideas??:) by Anonymous Monk

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.