1

我正在使用String::Approx从其他列表中找到最相似的匹配项。我惊喜地发现您可以使用amatch()数组与数组进行比较,尽管该功能没有记录在案;我准备编写自己的函数来做到这一点。我更惊讶地发现元素的顺序并不重要。但是,即使amatch()工作完美无缺,我在adist(). 考虑以下程序:

#! /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']and ['hawk', 'shark']),但它不能告诉我距离。最终目标是按距离对比赛进行排序并选择最喜欢的比赛@matchstr。实际上是否amatch()像我认为的那样工作,或者我只是使用了过于简单的输入?为什么不amatch()工作?

4

2 回答 2

3

您不能将数组作为第一个参数传递给 amatch 或 adist 并使其按预期工作。

数组被解包到列表中,所以 amatch 看到的东西amatch( 'cat', 'dog', 'rat', 'hog' )当然不是你想要的。

您必须创建支持数组引用作为第一个参数的新版本的 amatch 和 adist。然后,您需要将潜艇称为my_amatch(\@matchstr, @$_)

于 2011-05-17T21:11:54.370 回答
1

amatch 没有做你认为的那样。

如果您将 qw(cat dog) 更改为 qw(cat zzz) 您会得到相同的结果。

然后,如果您将“hawk”、“shark”更改为“hawk”、“zzz”,您仍然会得到相同的结果。

看起来它只是在与“猫”进行比较。

于 2011-05-17T21:55:59.967 回答