2

有 2 个哈希列表:

my  @family1= (
{
   husband  => "barney",
   wife     => "betty",
   son      => "bamm bamm",
},
   husband => "george",
   wife    => "jane",
   son     => "elroy",
},
);

my @family2{
   wife    => "jane",
},
);

两个列表中的键结构不同,我需要获取不在@family1 中的键“妻子”,例如在本例中为“贝蒂”。

我曾想过做类似的事情:

foreach my $f1(@family1)
{
   foreach my $f2 (@family2)
   {
     if (($f1->{wife} ne $f2 -> {wife})
      { 
       print MYFILE Dumper ($f1->{wife});
      }
   }
}

当我做类似的事情时,并没有得到我的期望。我得到 n 次 f1->{wife} 并且我想得到:

@sameWife = ("betty");

有没有人有更好的解决方案?谢谢

4

2 回答 2

1
my @sameWife = grep {
      my $wife = $_;                         # wife from @family1
      grep { $wife ne $_->{wife} } @family2; # take $wife if she isn't in @family2
    }
    map { $_->{wife} }                       # we want just wife, not whole hash
    @family1;

或者更容易阅读:

my @sameWife = map {
      my $wife = $_->{wife};        # wife from @family1
      my $not_in_family2 = grep { $wife ne $_->{wife} } @family2;
      $not_in_family2 ? $wife : (); # take $wife if she isn't in @family2
    }
    @family1;
于 2013-05-13T14:48:50.600 回答
1

不同的方法:

my %foo; # temp hash
# only use the wife from each has; parens are to seperate the two maps
$foo{$_}++ for ( map { $_->{wife} } @family1 ), map { $_->{wife} } @family2;
# only use the names that appear once
print grep { $foo{$_} == 1 } keys %foo;
于 2013-05-13T14:57:31.383 回答