Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Logical operations on arrays

by MidLifeXis (Monsignor)
on Oct 04, 2012 at 12:21 UTC ( [id://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

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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (2)
As of 2024-04-19 18:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found