Reputation: 6350
I have two array of hashes.They are as below
my $arr1 =[{'mid_id' => '1'},{'mid_id' => '2'},{'mid_id' => '5'} ];
my $arr2 = [{'name' => 'Name1','id' => '1'},{'name' => 'Name2','id' => '2'},{'name' => 'Name6','id' => '6'}];
Now i want to get the name from the second array whose id matches two the first array. I have tried by this way but i want to make this code more better is there any way to do this
foreach my $a1(@$arr1){
foreach (@$arr2){
if($_->{id} eq $a1->{mid_id}){
print "$_->{id} mapped to $_->{name} \n";
} else{
print "no match $_->{id} \n";
}
}
Upvotes: 0
Views: 534
Reputation: 35198
You could use grep
like the following. The only trick is that you need to test if you actually found a match:
use strict;
use warnings;
my @array = (
{ 'mid_id' => '1' },
{ 'mid_id' => '2' },
{ 'mid_id' => '5' },
};
my @recs = (
{ 'name' => 'Name2', 'id' => '1' },
{ 'name' => 'Name', 'id' => '2' },
{ 'name' => 'VP', 'id' => '3' },
);
for my $hash (@array){
my ($rec) = grep {$hash->{mid_id} eq $_->{id}} @recs;
print "$hash->{mid_id} mapped to " . ($rec ? $rec->{name} : "<No Match>") . "\n";
}
Outputs:
1 mapped to Name2
2 mapped to Name
5 mapped to <No Match>
Upvotes: 2