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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.