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) != -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;
}
