A solution to the first task of the 18th Perl Weekly Challenge.
Write a script that takes 2 or more strings as command line parameters and print the longest common substring. For example, the longest common substring of the strings “ABABC”, “BABCA” and “ABCBA” is string “ABC” of length 3. Other common substrings are “A”, “AB”, “B”, “BA”, “BC” and “C”. Please check this wiki page for details.
sub substrings($_, \len) {
gather for 0 .. (.chars - len) -> \offset {
take .substr(offset, len);
}
}
sub MAIN(*@strings where .so) {
for @strings>>.chars.min ... 1 -> \len {
my @common-substrings = keys [∩] @strings>>.&substrings(len);
if @common-substrings {
.perl.put for @common-substrings.sort;
last;
}
}
}