mamesaye
mamesaye

Reputation: 2153

perl how to use exists to check if hash is in array of hashes

i have two array of hashes: AH1 and 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
          }  
        ];  

how can i print hashes of AH1 that are in AH2 using Perl exists Function? or without having to iterate in the array.

Upvotes: 0

Views: 2185

Answers (1)

ikegami
ikegami

Reputation: 385655

exists locates by index, which are 0,1,2, and not 123,1389,779. exists can't help.

Furthermore, you must iterate over both array (one way or another) unless you switch one of the arrays to a hash.

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

In fact, switching is the easiest way to solve this.

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

It's also quite efficient: You iterate over each array only once.

Upvotes: 1

Related Questions