{ foreach ($_) { if (/\G (?= >>> )/xgc) { # Substitution supressed by following ">>". redo if /\G >>> [^\n]* \n (?= >> (?!>) ) /xcg; # Do substitution. s/\G >>>/PYTHON_PROMPT/xcg; # Go process next line. /\G [^\n]* \n /xcg; redo; } # Substitution prevented by preceeding ">>" /\G >> (?!>) [^\n]* \n >>> [^\n]* \n /xcg && redo; # ^^^^^ optional due to statement order. # Go process next line. m/\G [^\n]* \n /xcg && redo; } print; print("==========\n"); }