简体   繁体   中英

Compare Two Arrays using Grep in perl

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";
        }
}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM