# ðŸ“˜ Finding the longest common substring using Perl 6

Find the longest common substring in the given two strings.

Let us limit ourselves with finding only the first longest substring. If there are more common substrings of the same length, then the rest are ignored. There are two loops (see also Task 17,Â The longest palindrome) over the first string (`\$a`), and they use theÂ indexmethod to search for the substring in the second string (`\$b`).

`my \$a = 'the quick brown fox jumps over the lazy dog';my \$b = 'what does the fox say?';my \$common =Â '';for 0 .. \$a.chars -> \$start {Â Â Â Â for \$start .. \$a.chars - 1 -> \$end {Â Â Â Â Â Â Â Â my \$s = \$a.substr(\$start, \$a.chars - \$end);Â Â Â Â Â Â Â Â if \$s.chars > \$common.chars && \$b.index(\$s).defined {Â Â Â Â Â Â Â Â Â Â Â \$common = \$s;Â Â Â Â Â Â Â Â }Â Â Â Â }}say \$commonÂ Â Â Â Â ?? "The longest common substring is '\$common'."Â Â Â Â Â !! 'There are no common substrings.';`

The `index` method returns the position of the substringÂ `\$s` if it is found in the stringÂ `\$b`. It is a little bit tricky to check if the substring is found because when it is found at the beginning of the string, then the returned value isÂ 0 (asÂ 0 is the position of the substring). If the substring is not found, thenÂ `Nil` is returned.Â `Nil` is not a numeric value; thus, it cannot be compared using theÂ `==` orÂ `!=` operators. Use theÂ `defined` method to check ifÂ `index` returns a value, notÂ `Nil`:Â `\$b.index(\$s).defined`.

## 3 thoughts on “ðŸ“˜ Finding the longest common substring using Perl 6”

1. Can’t decide if I like this version better or worse than yours:

```my \$a = 'the quick brown fox jumps over the lazy dog';
my \$b = 'what does the fox say?';

sub length-sorted-substrs(\$a) {
gather for \$a.chars, *-1 ... 1 -> \$l {
for 0 .. \$a.chars - \$l -> \$n {
take \$a.substr(\$n, \$l);
}
}
}

for length-sorted-substrs(\$a) -> \$aa {
if \$b ~~ / "\$aa" / {
say "Longest common substring is *\$aa*";
exit;
}
}

say "There are no common substrings.";```

Like

1. andrewshitov says:

Fixed ðŸ™‚

Like