Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Matching elements inside two arrays

by Athanasius (Bishop)
on Apr 10, 2019 at 06:33 UTC ( #1232382=note: print w/replies, xml ) Need Help??

in reply to Matching elements inside two array

Hello ameezys, and a belated welcome to the Monastery!

You are using grep incorrectly. The block is applied to each element of the array in turn, setting $_ to that element. So

grep { @input_B eq $_ } @input_array

is testing each element of @input_array against @input_B, which makes no sense. You need something along these lines:

for my $inputKey (@input_array) { if (grep { $inputKey eq $_ } @input_A) ... }

As Marshall says, your requirements are not clear. I’m guessing you want to add an element to the hash %primaryCC0 when, and only when, that element is common to all three input arrays. In which case, the any function in List::Util is more efficient than grep:

use strict; use warnings; use List::Util qw( any ); my @input_array = qw( N1 N2 N3 N6 N7 ); my @input_A = qw( N1 N3 N11 N11 N10 N16 ); my @input_B = qw( N3 N6 N2 N7 N16 N19 ); my %primaryCC0; for my $inputKey (@input_array) { if (any { $_ eq $inputKey } @input_A) { if (any { $_ eq $inputKey } @input_B) { @{ $primaryCC0{$inputKey} } = (1, 1); } else { print "$inputKey: only 1 input is PI\n"; } } else { print "$inputKey: this is a wire\n"; } } for my $key (sort keys %primaryCC0) { my ($CC0, $CC1) = @{ $primaryCC0{$key} }; print "CC0[$key] = $CC0\n"; print "CC1[$key] = $CC1\n"; }


16:27 >perl N1: only 1 input is PI N2: this is a wire N6: this is a wire N7: this is a wire CC0[N3] = 1 CC1[N3] = 1 16:27 >

Note that although @{ $primaryCC0{$inputKey} } = (1, 1); works (because of Perl’s autovivification), I would prefer to use:

$primaryCC0{$inputKey} = [1, 1];

which makes the creation of an anonymous array explicit.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2020-07-12 09:54 GMT
Find Nodes?
    Voting Booth?

    No recent polls found