print "$1 method $2\n" while $x =~ /^([AB])(.+)$/mg; #### # always match the entire string, running your code on matching lines /^(?: (?: ([AB]) (.+) (?{ print "$1 method $2\n"; }) | .* ) \n? )*/x