in reply to Re: Regexp help
in thread Regexp help

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

Replies are listed 'Best First'.
Re^3: Regexp help
by Anonymous Monk on Sep 16, 2011 at 20:57 UTC

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