>perl -wMstrict -le "for my $s (qw( B111 B111B111 B111B111B111 A111 A111A111 A111A111A111 A111B111 A111B111A111 A111B111A111B111 A111B111A111B111A111 B111A111 B111A111B111 B111A111B111A111 B111A111B111A111B111 B BB BBB A AA AAA BA BAB AB ABA xxx xx x), '', ) { local our $y_n; ()= $s =~ m{ ([AB]) (?{ $y_n = $^N eq 'A' ? 'yes' : 'no' }) }xmsg; if (defined $y_n) { printf qq{%3s: '%s' \n}, $y_n, $s; } else { warn qq{no A or B found in '$s'}; } } " no: 'B111' no: 'B111B111' no: 'B111B111B111' yes: 'A111' yes: 'A111A111' yes: 'A111A111A111' no: 'A111B111' yes: 'A111B111A111' no: 'A111B111A111B111' yes: 'A111B111A111B111A111' yes: 'B111A111' no: 'B111A111B111' yes: 'B111A111B111A111' no: 'B111A111B111A111B111' no: 'B' no: 'BB' no: 'BBB' yes: 'A' yes: 'AA' yes: 'AAA' yes: 'BA' no: 'BAB' no: 'AB' yes: 'ABA' no A or B found in 'xxx' at -e line 1. no A or B found in 'xx' at -e line 1. no A or B found in 'x' at -e line 1. no A or B found in '' at -e line 1.