I have a string that looks like key: value pairs. A couple of the keys are "headings". I want to:
- Add a space above the first heading
- Indent everything from the 1st heading to the 2nd heading by 2 spaces
- Indent everything from the 2nd heading to the end of the section by 2 spaces
The heading names and end-of-section keys are known.

Here is what I came up with. It works as desired, but seems to me mighty inefficient as it traverses the string #-of-headings * #-of-items-to-indent times. I wonder if it can be done in fewer iterations...

#!/usr/bin/perl local $/ = undef; my $string = <DATA>; $string =~ s/^(Heading Here:)$/\n$1/m; while ( $string =~ s/^(Heading Here:.*\n)(\S.+)(\nAnother Heading:)$/$ +1 $2$3/gsm ) {} while ( $string =~ s/^(Another Heading:.*\n)(\S.+)(\nEnd of section:)/ +$1 $2$3/gsm ) {} print $string; __DATA__ Key: Value Item: Another Item: Text Etc Etc: Whatever Heading Here: Indent This: Stuff By 2 spaces: Every line: Until The Next: Heading Efficiently: If possible Another Heading: More: Stuff: To: Indent End of section: Stop indenting Random: Test There: Is more stuff Further down: The string

Output:

Key: Value Item: Another Item: Text Etc Etc: Whatever Heading Here: Indent This: Stuff By 2 spaces: Every line: Until The Next: Heading Efficiently: If possible Another Heading: More: Stuff: To: Indent End of section: Stop indenting Random: Test There: Is more stuff Further down: The string

In reply to Regexp help by thewebsi

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.