How to get elements of first array of hashes that not present in second array of hashes in Perl -
how elements of first array of hashes not present in second array of hashes. example, have 2 arrays of hashes:
my $arr1 = [ { id => 1, name => 'element 1'}, { id => 2, name => 'element 2'}, { id => 3, name => 'element 3'}, { id => 4, name => 'element 4'}, { id => 5, name => 'element 5'}, ]; $arr2 = [ { id => 1, name => 'element 1'}, { id => 3, name => 'element 3'}, { id => 5, name => 'element 5'}, ];
result should be:
my $arr3 = [ { id => 2, name => 'element 2'}, { id => 4, name => 'element 4'}, ];
you can build hash look-up , filter @$arr1
elements,
my %seen; @seen{ map $_->{id}, @$arr2 } = (); # $seen{$_->{id}} = undef @$arr2; # or foreach instead of hash slice $arr3 = [ grep{ !exists $seen{$_->{id}} } @$arr1 ];
Comments
Post a Comment