in reply to Regexp help

This uses the range operator:

use strict; use warnings; my $head_re = qr/^(?:Heading Here|Another Heading):/; my $end_re = qr/^End of section:/; while (<DATA>) { 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; }

Replies are listed 'Best First'.
Re^2: Regexp help
by thewebsi (Scribe) on Sep 17, 2011 at 07:57 UTC

    This didn't run as fast as the previously posted solution. It took me a while to wrap my head around the range operator, but I modified the code as follows, and now it runs faster than Kc12349's solution, though not quite as fast as ikegami's:

    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; }

    I do find this solution quite elegant though - thanks!