if ($string =~ /(foo(?{ $N = 1 }))|(bar(?{ $N = 1 }))/) { if ($N == 1) { ... } else { ... } }