2013-03-28 60 views
0

我有兩個哈希的數組。我想比較兩個數組散列中的鍵是否包含相同的值。比較兩個哈希的數組之間的值

#!/usr/bin/perl 
use warnings; use strict; 
my %h1 = (
     w => ['3','1','2'], 
     e => ['6','2','4'], 
     r => ['8', '1'], 
    ); 

my %h2 = (
     w => ['1','2','3'], 
     e => ['4','2','6'], 
     r => ['4','1'], 
    ); 

foreach (sort {$a <=> $b} (keys %h2)){ 
    if (join(",", sort @{$h1{$_}}) 
     eq join(",", sort @{$h1{$_}})) {  

     print join(",", sort @{$h1{$_}})."\n"; 
     print join(",", sort @{$h2{$_}})."\n\n"; 
    } else{ 
    print "no match\n" 
    } 
    } 


if ("1,8" eq "1,4"){ 
    print "true\n"; 
} else{ 
    print "false\n"; 
} 

輸出被認爲應該是:

2,4,6 
2,4,6 

1,2,3 
1,2,3 

no match 
false 

但由於某種原因我if-statement不工作。感謝

+0

你的條件語句在工作中。 – kjprice

回答

2

智能匹配是一個有趣的解決方案;可從5.010向前:

if ([sort @{$h1{$_}}] ~~ [sort @{$h2{$_}}]) { ... } 

智能匹配上陣列的引用時,每個陣列的對應元件smartmatch自己返回true。對於字符串,智能匹配測試字符串相等。

這可能比join要好,因爲智能匹配適用於任意數據*。在另一方面,智能匹配是相當複雜的,具有hidden gotchas


*上的任意數據:如果你能保證您的所有字符串只包含數字,那麼一切都還好吧。但是,那麼你可以只使用了用數字代替:

%h1 = (w => [3, 1, 2], ...); 
# sort defaults to alphabetic sorting. This is undesirable here 
if ([sort {$a <=> $b} @{$h1{$_}}] ~~ [sort {$a <=> $b} @{$h2{$_}}]) { ... } 

如果您的數據可以包含任意字符串,尤其是含commata字符串,那麼你的對比是不是安全的 - 考慮到陣列

["1foo,2bar", "3baz"], ["1foo", "2bar,3baz"] # would compare equal per your method 
+0

我該如何擺脫警告信息? '參數「e」在排序中不是數字' – cooldood3490

+1

@ cooldood3490要按字母順序排序,請使用'cmp'運算符而不是'<=>',或省略'sort'中的代碼塊 - 字母排序是默認值 – amon

1
if (join(",", sort @{$h1{$_}}) 
    eq join(",", sort @{$h1{$_}})) { 

應該是:

if (join(",", sort @{$h1{$_}}) 
    eq join(",", sort @{$h2{$_}})) { 

注意$h2。你正在比較一個哈希自己。

+0

如何擺脫警告信息? '參數「e」在排序中不是數字# – cooldood3490

+0

@ cooldood3490噢,第一種排序應該是'sort {$ a cmp $ b}' – kjprice

+1

@ cooldood3490'cmp'用於比較詞法(按字母順序)和'<=>'用於比較數字。 – kjprice

0

試試這個:它將兩個哈希值逐行比較。

if ( join(",", sort @{ $h1{$_}}) 
     eq join(",", sort @{ $h2{$_}})) #Compares two lines exactly