in reply to Regexp help

Seems to me this would be quite easy to implement reading a line at a time. Just keep a flag indicating whether you should be indenting or not.

while (<>) { if ( /^Heading Here:/ ) { $_ = "\n" . $_; $indent = 1; } elsif ( /^Another Heading:/ ) { $indent = 1; } elsif ( /^End of section:/ ) { $indent = 0; } elsif ( $indent ) { $_ = " " . $_; } print; }

Replies are listed 'Best First'.
Re^2: Regexp help
by Kc12349 (Monk) on Sep 16, 2011 at 19:45 UTC

    I agree. I might even take it a step further and write it with an eye for maintainability and allow myself to easily add new headings as needed.

    my @new_line_strings = ( 'Heading Here', ); my @opening_strings = ( 'Heading Here', 'Another Heading', ); my @closing_strings = ( 'End of section', @opening_strings, ); my $new_line_pattern = '^(?:' . join('|', @new_line_strings) . ')'; my $opening_pattern = '^(?:' . join('|', @opening_strings) . ')'; my $closing_pattern = '^(?:' . join('|', @closing_strings) . ')'; while ( defined (my $line = <DATA> ) ) { state $indent_char = ''; $indent_char = '' if $line =~ m/$closing_pattern/; print "\n" if $line =~ m/$new_line_pattern/; print $indent_char . $line; $indent_char = ' ' if $line =~ m/$opening_pattern/; }

      This tweak adds a newline to the first heading in a series:

      while ( defined (my $line = <DATA> ) ) { state $indent_char = ''; print "\n" if $line =~ m/$opening_pattern/ && ! $indent_char; $indent_char = '' if $line =~ m/$closing_pattern/; print $indent_char . $line; $indent_char = ' ' if $line =~ m/$opening_pattern/; }