#!/usr/bin/perl

sub naive_string_matcher {
    my ( $big, $sub ) = @_; # The big and the substring.

    use integer;        # For extra speed.

    my $big_len = length( $big );
    my $sub_len = length( $sub );

    return -1 if $big_len < $sub_len;   # Pattern too long!

    my ( $i, $j, $match_j );
    my $last_i = $big_len - $sub_len;
    my $last_j = $sub_len - 1;

    for ( $i = 0; $i <= $last_i; $i++ ) {
        for ( $j = 0, $match_j = -1;
              $j < $sub_len &&
              substr( $sub, $j, 1 ) eq substr( $big, $i + $j, 1 );
              $j++ ) {
           $match_j = $j;
        }
        return $i if $match_j == $last_j; # A match.
    }

    return -1; # A mismatch.
}

print naive_string_matcher( "abcdefgh", "def" ), " ",
      naive_string_matcher( "abcdefgh", "deg" ), "\n";
