foreach ( split ( /^/m, $string ) ) { state $saw = 0; if ( my $seq = ( /^Heading Here:$/ .. /^Another Heading:$/ or /^Another Heading:$/ .. /^End of section:/ ) ) { redo if $seq =~ /E0$/; print $seq != 1 ? " " : ! $saw++ ? "\n" : ""; } print; }