my $state = 'no'; my $string = 'A111B111A111B111'; while( $string =~ m/ (? (?[AB]) (?\d+) ) /gx ) { $state = $+{condition} eq 'A' ? 'yes' : 'no'; print "($+{chunk}) => State: ($state) => Value ($+{value})\n"; }