I would not call this efficient. I have concerns regarding this scaling up, but I've not yet had reason to check it out.
This does seen to be the kind of idiomatic solution you implied you wanted.

UPDATE: More details on the data set being manipulated make me more cautious about the suitability of this code. If efficiency is really a problem and the differences and intersection of the arrays are all desired my first question would be Are these arrays ordered, as in your example?

#!/usr/bin/perl use warnings; use strict; my @one = ( 1, 2, 3, 4); my @two = ( 2, 4, 6, 8); my (%in_one, %in_two, @in_both, @only_in_one, @only_in_two); @in_one{ @one} = 1; @in_two{ @two} = 1; @in_both = grep { exists $in_one{$_} } @two; @only_in_one = grep { not exists $in_two{$_}} @one; @only_in_two = grep { not exists $in_one{$_}} @two; local $, = " "; print "\@one ", @one, "\n"; print "\@two ", @two, "\n"; print "\@only_in_one ", @only_in_one, "\n"; print "\@only_in_two ", @only_in_two, "\n"; print "\@in_both ", @in_both, "\n"; __DATA__ @one 1 2 3 4 @two 2 4 6 8 @only_in_one 1 3 @only_in_two 6 8 @in_both 2 4

In reply to Re: Efficient Comparison of Array elements by rir
in thread Efficient Comparison of Array elements by aging acolyte

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.