在perl中使用Grep比较两个数组

时间:2014-06-11 05:48:08

标签: arrays perl

我有两个哈希数。它们如下所示

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'}];

现在我想从第二个数组获取名称,其id与第一个数组匹配。 我已经尝试过这种方式,但我想让这个代码更好,有没有办法做到这一点

foreach my $a1(@$arr1){

foreach (@$arr2){
        if($_->{id} eq $a1->{mid_id}){
                print "$_->{id} mapped to  $_->{name} \n";
        } else{
                print "no match $_->{id} \n";
        }
}

1 个答案:

答案 0 :(得分:2)

您可以使用grep,如下所示。唯一的诀窍是你需要测试你是否真的找到了匹配项:

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

输出:

1 mapped to Name2
2 mapped to Name
5 mapped to <No Match>