http://www.perlmonks.org?node_id=997227


in reply to Logical operations on arrays

If the order of the arrays makes no difference, it sounds like you are looking for an intersection operator of some sort. Array::Utils might have what you are looking for. I found this by searching metacpan for "union intersect".

Otherwise, a method to find them is pretty straightforward:

There are a couple of assumptions built into the above (@arrayN does not contain an undef value, and the second array only has unique values).

Updates:

  1. Added example code
  2. Added search example
  3. D'oh - quite right Jenda. I have got to stop writing code before my first cup of coffee. :-/

--MidLifeXis

Replies are listed 'Best First'.
Re^2: Logical operations on arrays
by Athanasius (Archbishop) on Oct 04, 2012 at 12:24 UTC
Re^2: Logical operations on arrays
by Jenda (Abbot) on Oct 04, 2012 at 23:03 UTC

    There's no reason to work hard to set the values in the hash to ones, leave them undefined and use exists() within the grep{}. Also there is no reason to push the elements into the @intersection, just assign them.

    my %hash1; @hash1{@array1} = (); my @intersection = grep {exists $hash1{$_} } @array2;

    Jenda
    Enoch was right!
    Enjoy the last years of Rome.