Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

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]
[GotToBTru]: you are correct, choroba, but of course there is no point in doing one without the other
[GotToBTru]: un less you're working on write-only memory
[1nickt]: my $x = $aohoaoh->[0]->{' foo'}->[0]->{'bar' }; should work
[thepkd]: not indexing
[thepkd]: getting data out of the ds
[choroba]: it depends. Give more details, please
[thepkd]: i used a series of {}'s but it dont work
[choroba]: You need square brackets for arrays
[GotToBTru]: you can certainly construct a single expression to access any part of the data structure, without using temp variables. but you might make it easier on yourself and any other poor soul who has to understand your code if you do
[thepkd]: to dereference i mean

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (14)
As of 2016-12-06 13:21 GMT
Find Nodes?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:

    Results (104 votes). Check out past polls.