#!/usr/bin/perl -w

use v5.38;

sub valid($pat, @l) {
	my $re = '\A[^#]*' . join('[^#]+', map { "#{$_}" } @l) . '[^#]*\z';
	# say "$pat =~ /$re/   @l";
	return $pat =~ /$re/;
}

sub walk($pat, @l) {
	my $p = $pat;
	my $sum = 0;
	if ($p =~ s/\?/./) {
		$sum += walk($p, @l);
		$p = $pat;
		$p =~ s/\?/#/;
		$sum += walk($p, @l);
	} elsif (valid($pat, @l)) {
		$sum = 1;
	}
	return $sum;
}

my $sum;
while (<>) {
	chomp;
	my ($pattern, $list) = split / /;
	my @list = $list =~ /\d+/g;

	my $s = walk($pattern, @list);
	say "$pattern @list = $s";
	$sum += $s;
}
say $sum;
