use strict; use warnings; my $head_re = qr/^(?:Heading Here|Another Heading):/; my $end_re = qr/^End of section:/; while () { state $saw = 0; if (my $seq = /$head_re/ ... /$head_re|$end_re/) { if ($seq == 1) { s/^/\n/ unless $saw++; } elsif ($seq =~ /E0$/) { $saw = 0 if /$end_re/; redo; } else { s/^/ /; } } print; }