aboutsummaryrefslogtreecommitdiff
path: root/challenge-081/jo-37/perl/ch-1.pl
blob: 61941ab41545df6d11b46032448ae52371992de3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/perl

use Test2::V0;

# Find common base strings in two given strings.
sub cbs {

	# Combine both strings by joining them with a newline.
	# The strings must not contain newlines.
	local $_ = shift . "\n" . shift;

	# Collect all common base strings.
	# Note: "dot" does not match a newline here.
	my @base;
	m{
		^ (.+?) \1*+ \n \1++ \z	# capture base string for both
		(?{push @base, $1})		# collect captured base string
		(*FAIL)					# force backtracking
	}x;

	@base;
}

is [cbs("abcdabcd", "abcdabcdabcdabcd")], ["abcd", "abcdabcd"],
	"first example";

is [cbs("aaa", "aa")], ["a"], "second example";

is [cbs("abcabc", "abcdabcdabcd")], [], "no common base strings";

done_testing;