2011-05-17 43 views
1

我使用String::Approx從其他列表中找出最相似的兩個數組的數組。我驚喜地發現,您可以使用amatch()將數組與數組進行比較,儘管該功能未被記錄;我準備寫我自己的功能來做到這一點。我更驚訝地發現元素的順序並不重要。但是,儘管amatch()完美無瑕,但我在adist()上遇到困難。考慮下面的程序:perl字符串::大約在數組

#! /usr/bin/perl 

use String::Approx qw (amatch adist); 

@matches = qw(); 
%matchhash = qw(); 
@matchstr = qw(cat dog); 
@poss = (['rat', 'hog'], 
    ['gnat', 'frog'], 
    ['giraffe', 'elephant'], 
    ['dig', 'bat'], 
    ['catatonic', 'doggone'], 
    ['care', 'dog'], 
    ['care', 'ding'], 
    ['hawk', 'shark']); 

@matches = grep { amatch (@matchstr, @$_) } @poss; 

foreach $k (@matches) 
{ 
    $dist = adist(@matchstr, @$k); 
    print "@matchstr has a difference from @$k of $dist \n"; 
} 

這裏就是它輸出:

cat dog has a difference from rat hog of 3 
cat dog has a difference from gnat frog of 3 
cat dog has a difference from dig bat of 3 
cat dog has a difference from catatonic doggone of 3 
cat dog has a difference from care dog of 3 
cat dog has a difference from care ding of 3 

所以,這似乎是選擇正確的答案(它忽略['giraffe', 'elephant']['hawk', 'shark']),但它不能告訴我距離。最終目標是按距離排列比賽並挑選最像@matchstr的比賽。是amatch()實際上工作以及我認爲它,或者我只是使用太簡單的輸入? amatch()爲什麼沒有工作?

回答

3

您不能將數組作爲第一個參數傳遞給amatch或adist,並按照您的預期工作。

數組解壓縮到列表中,所以看起來像amatch('cat', 'dog', 'rat', 'hog')這當然不是你想要的東西。

您將不得不創建支持數組引用作爲第一個參數的新版本的amatch和adist。然後你需要調用潛水艇my_amatch(\@matchstr, @$_)

+0

好吧,我理解你的迴應,但我仍然模糊了爲什麼amatch()似乎工作正常。 – 2011-05-17 21:36:02

1

amatch不會做你認爲的事情。

如果您將qw(貓狗)更改爲qw(貓zzz),您會得到相同的結果。

然後,如果你改變「鷹」,「鯊魚」爲「鷹」,「zzz」你仍然會得到相同的結果。

它看起來只是在和「貓」做比較。