Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Logical operations on arrays

by MidLifeXis (Prior)
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).

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


Comment on Re: Logical operations on arrays
Select or Download Code
Re^2: Logical operations on arrays
by Athanasius (Monsignor) 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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://997227]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (8)
As of 2014-12-29 14:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (188 votes), past polls