perl如何使用exists来检查hash是否在hashes数组中



我有两个散列数组:AH1和AH2。

$AH1 = [  
          {
            'id' => 123,  
            'name' => abc
          },  
          {
            'id' => 456,  
            'name' => def
          },  
          {
            'id' => 789,  
            'name' => ghi
          },  
          {
            'id' => 101112,  
            'name' => jkl
          },  
          {
            'id' => 1389,  
            'name' => mno
          }  
        ];  
$AH2 = [  
          {
            'id' => 123,  
            'name' => abc
          },  
          {
            'id' => 1389,  
            'name' => mno
          },  
          {
            'id' => 779,  
            'name' => ghi
          }  
        ];  

如何使用Perlexist函数打印AH2中的AH1哈希?或者不必在数组中迭代。

exists通过索引定位,索引为0,1,2,而不是1231389779。exists也无能为力。

此外,除非将其中一个数组切换为散列,否则必须对这两个数组进行迭代(以某种方式)。

$HH2 = {
   123 =>  {
             'id' => 123,  
             'name' => abc
           },  
   1389 => {
            'id' => 1389,  
            'name' => mno
           },  
   779  => {
             'id' => 779,  
             'name' => ghi
           }
};

事实上,切换是解决这一问题的最简单方法。

my %HH2 = map { $_->{id} => $_ } @$AH2;
for (@$AH1) {
    print "$_->{id} in bothn"
       if $HH2{ $_->{id} };
}

它也非常高效:每个数组只迭代一次。

最新更新