Hello, I would like the Knuth - Morris - Pratt algorithm implemented in Perl. And 2 subs already have written it. The prefix sub and sub match, but the do not seem to be correct. But I honestly do not know so here is exactly the problem. Could someone please give me the hint where he is and maybe the correction? lg Bells
#!/usr/bin/perl use strict; use warnings; # Prefix sub ermorde_Knuth_next{ my($P)=@_; # Pattern use integer; my$m=(0..lenght($P)-1); my$i=0; my$j=-1; my @next; # Array for ($next[0] = -1; $i < $m; ) { 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); # lenght off pattern und der Prefix functio +n } # Matcher sub ermorde_Knuth { #knuth_morris_pratt Subroutine my ( $T, $P ) = @_; # text und pattern. use integer; my $m = ermorde_Knuth_next( $P ); #knuth_morris_pratt_next my ( $n, $i, $j ) = (length($T), 0, 0 ); my @next; while ( $i < $n ) { while ( $j > -1 && substr( $P, $j, 1 ) ne substr( $T, $i, 1 ) ) { $j = $next[ $j ]; } $i++; $j++; return $i - $j if $j >= $m; # Match } return -1;} # Mismatch
In reply to Knuth Morris Pratt by Bells
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |