Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Logical operations on arrays

by MidLifeXis (Monsignor)
on Oct 04, 2012 at 12:21 UTC ( #997227=note: print w/replies, xml ) Need Help??

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:

  • configure a hash for the first array (*)
    @hash1{@array1} = (1)x@array1
    This configures a hash %hash1 to have a true value for all values found in @array1. (* - This is probably clearer as $hash1{$_} = 1 for @array1)
  • loop through the second array picking out those elements that show up in the first array
    push( @intersection, grep { $hash1{$_} } @array2 );
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).


  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. :-/


Replies are listed 'Best First'.
Re^2: Logical operations on arrays
by Athanasius (Chancellor) 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;

    Enoch was right!
    Enjoy the last years of Rome.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://997227]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (9)
As of 2018-06-23 14:09 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.