Mike Blezien wrote:

I have two arrays, IE:

@arrayA = qw(1 3 5 6);

@arrayB = qw(2 3 6 4);

what I am attempting to do is finding a match from @arrayA in @arrayB
... what is the best way to accomplish this?

Hi Mike.

I assume you mean to find all values that appear in both arrays? I also assume
that the values in both arrays are unique, i.e. they occur only once in either
array?

There's the obvious way: for each element in @arrayA look through all the
elements in @arrayB to see if there's a matching value.


my @inboth;

foreach my $inA (@arrayA) {
 foreach my $inB (@arrayB) {
   push @inboth, $inA if $inB == $inA;
 }
}


And there's the nicer, more Perlish way, which is to use a hash to store a
temporary copy of @arrayA which will allow a simpler and faster check for the
elements in @arrayB.


my @inboth = do {
 my %inA = map { $_, 1 } @arrayA;
 grep $inA{$_}, @arrayB;
};


Which one you use is up to you. You may well find the first option quicker if
you're only expecting arrays of the size you show. In any case, the rule should
be to code the clearest and most obviously correct (to you) solution, and then
speed it up if it runs too slowly.

HTH,

Rob

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to