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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |