sub repeated_substring {
  my($str) = @_;

  my $half = int(length($str) / 2);
  my $offset1 = $half;
  my $offset2 = length($str) - $half;

  my $min = 1;
  my $substr = '';

 OFFSET:
  while ($offset1 and $min <= $offset1) {
    foreach my $offset ($offset1, $offset2) {
      my $tmp = substr($str, 0, length($str) - $offset) ^
                substr($str, $offset);

      while ($tmp =~ /(\0{$min,})/g) {
        my $len = length $1;
        $len = $offset1 if $len > $offset1;
        $substr = substr($str, pos($tmp) - length $1, $len);
        $min = length($substr) + 1;
        last OFFSET if $min > $offset1;
      }
    }
    $offset1--;
    $offset2++;
  }

  return $substr;
}
