Howdy, Stranger!

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

Categories

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

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