    sub repeated_substring {
        my $string  = shift;
        my $len     = length($string);
        my $longest = $len / 2;
        my $substring;
        my $offset = 1;
        LENGTH: for my $l (1 .. $longest) {
            my $num = $len - $l - 1;
            for ($offset .. $num) {
                my $sub = substr $string, $_ - 1, $l;
                # once the substring is longer than the string
                # we compare it against, we can last out because
                # it can't match
                last LENGTH if length($sub) > length($string) - $_ - $l;
                index($string, $sub, $_ + $l) != -1
                    and $substring = $sub
                    and $offset = $_
                    and next LENGTH;
            }
            # we didn't find a substring of given length:
            # that means we can't find a substring of a bigger length either
            last if length($substring) < $l;
        } 
        return $substring;
    }

__END__


Given the word "bananaannaaaba", it tests these substrings (on the left)
and does an index() test against the string on the right:

    b           ananaannaaaba 
    ba          nanaannaaaba
    ban         anaannaaaba     # no match!
    ana         naannaaaba      # no match!
    nan         aannaaaba       # no match!
    ana         annaaaba        # no match!
    naa         nnaaaba 
    naan        naaaba          # no match!
    aann        aaaba           # no match!
    anna        aaaba           # no match!
    
And no we are done because we can neither have a substring that is one
character more to the right and at the same time leaving a remainder
large enough nor can we test substrings with length of 5 because that
would be longer than the string itself.

So the idea is to make matching substrings one character longer...when
they don't match, shift the substring one two the right and test this
one. On each of these operations we can shorten the original string
because we naturally only compare the substring with what comes right of
it.

