1
我想在Perl中实现Knuth Morris Pratt algorithm。以下是我的代码,我将该算法的Perl第一版中的Mastering Algorithms引用。当我运行代码时,它会打印-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1。我哪里错了?Knuth Morris Pratt Perl中的算法实现
代码:
#!/usr/local/bin/perl
#text
my $seq = "babacbadbbac";
#pattern
my $motif = "acabad";
#pass the text and pattern to knuth_morris_pratt subroutine
my @res = knuth_morris_pratt($seq, $motif);
#print the result
print "The resulting array is:";
print "@res";
#computation of the prefix subroutine
sub knuth_morris_pratt_next
{
my($P) = @_; #pattern
use integer;
my ($m, $i, $j) = (length $P, 0, -1);
my @next;
for ($next[0] = -1; $i < $m;) {
# Note that this while() is skipped during the first for() pass.
while ($j > -1 && substr($P, $i, 1) ne substr($P, $j, 1)) {
$j = $next[$j];
}
$i++;
$j++;
$next[$i] = substr($P, $j, 1) eq substr($P, $i, 1) ? $next[$j] : $j;
}
return ($m, @next); # Length of pattern and prefix function.
}
#matcher subroutine
sub knuth_morris_pratt
{
my ($T, $P) = @_; # Text and pattern.
use integer;
my ($m,@next) = knuth_morris_pratt_next($P);
my ($n, $i, $j) = (length($T), 0, 0);
#my @next;
my @val;
my $k=0;
while ($i < $n)
{
while ($j > -1 && substr($P, $j, 1) ne substr($T, $i, 1))
{
$j = $next[$j];
}
$i++;
$j++;
if($j>=$m)
{
$val[$k]= $i - $j; # Match.
}
else
{
$val[$k]=-1; # Mismatch.
}
$k++;
}
return @val;
}
你试过用'perl -d your_script.pl'来调试它吗? – mvp 2013-05-11 19:27:55
它说:从perl5db.pl版本1.33加载DB例程 编辑器支持可用。 输入h或'h h'寻求帮助,或者'man perldebug'寻求更多帮助。 main::(q1.pl:3):\t my $ seq =“babacbadbbac”; DB <1> – 2013-05-11 19:37:44
太棒了。现在调试它。 'B Num' - 设置断点。 'r' - 启动程序。 'c' - 继续。 'p $ var' - 打印变量值。 'n' - 执行下一行。 ''' - 跳进程序。 '' - 重复上一个命令。 'l' - 打印 –
mvp
2013-05-11 19:40:39