$regex .= '(?{ print join(" ", map $$_, 1..$k), "\\n" })(?!)'; $string =~ /$regex/x;