my %captures; my $pat = join "", map { if ( $captures{ $_ } ) { "\\$captures{$_}" } else { my $capture = 1 + keys( %captures ); $captures{ $_ } = $capture; if ( $capture == 1 ) { "(.)" } else { "(?!".( join "|", map { "\\$_" } 1 .. $capture-1 ).")(.)" } } } split //, $template; my $re = qr/^$pat\z/s; #### my $template = "abcdefa"; #### ^ (.) (?!\1)(.) (?!\1|\2)(.) (?!\1|\2|\3)(.) (?!\1|\2|\3|\4)(.) (?!\1|\2|\3|\4|\5)(.) \1 \z