2013-05-13 27 views
2

有2所列出哈希:獲得2個不同lists'哈希值的差值在Perl

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

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

鍵的結構在兩個列表不同,我需要獲得關鍵的妻子「是不在@ family1中,例如在這種情況下「betty」。

我曾經想過做這樣的事情:

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

當我做類似的東西不明白我的期望。我得到n次f1 - > {太太},我只想得到:

@sameWife = ("betty"); 

有沒有人有更好的解決方案?由於

回答

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; 
+0

感謝。現在我想再添加一個條件:'我的$ not_in_family2 = grep {$ wife ne $ _-> {wife}和$ son eq「elroy」} @ family2;''eq'條件完美,但'ne'顯示所有元素。 – kmxillo 2013-05-14 15:49:57

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;