Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID


We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Problem wiht Sub

BelliBelli Posts: 1Member
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

use strict;
use warnings;

# Prefix

sub ermorde_Knuth_next{
my($P)=@_; # Pattern

use integer;


my @next; # Array

for ($next[0] = -1; $i < $m; ) {
while ( $j > -1 &&
substr( $P, $i, 1 ) ne substr( $P, $j, 1 ) ) {
$j = $next[ $j ];
$next[ $i ] =
substr( $P, $j, 1 ) eq substr( $P, $i, 1 ) ?
$next[ $j ] : $j;
return ($m,@next); # lenght off pattern und der Prefix function


# 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 ];
return $i - $j if $j >= $m; # Match
return -1;} # Mismatch
Sign In or Register to comment.