Is there a reason you don't use the database to join these two arrays? If you can't, you could use the following:
sub commonLists { my ( $array_ref1, $array_ref2, $elementToMatch ) = @_; my %lookup = map { $_->[$elementToMatch] => $_ } @$array_ref1; my @match; foreach my $fromArray2 (@$array_ref2) { my $fromArray1 = $lookup{$fromArray2->[$elementToMatch]}; push(@match, $fromArray1, $fromArray2) if $fromArray1; } return \@match; }
Or if the field is not a key:
sub commonLists { my ( $array_ref1, $array_ref2, $elementToMatch ) = @_; my %lookup; push(@{$lookup{$_->[$elementToMatch]}}, $_) foreach @$array_ref1; my @match; foreach my $fromArray2 (@$array_ref2) { my $fromArray1 = $lookup{$fromArray2->[$elementToMatch]}; push(@match, @$fromArray1, $fromArray2) if $fromArray1; } return \@match; }
But it won't work until you fix the bug in your code.
my @matchedLists = &commonLists( \$array_ref1, \$array_ref2, 2 );
should be
my @matchedLists = &commonLists( \@array1, \@array2, 2 );
or
my @matchedLists = &commonLists( $array_ref1, $array_ref2, 2 );
Your variable naming stayle is inconsistent. You use both fooBar and foo_bar for similar things. Be consistent.
In reply to Re: How to match specific elements of multiple array_references
by ikegami
in thread How to match specific elements of multiple array_references
by awohld
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |