thewebsi has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Regexp help
by ikegami (Patriarch) on Sep 16, 2011 at 19:33 UTC | |
by Kc12349 (Monk) on Sep 16, 2011 at 19:45 UTC | |
by Anonymous Monk on Sep 16, 2011 at 20:57 UTC | |
by thewebsi (Scribe) on Sep 16, 2011 at 21:41 UTC | |
|
Re: Regexp help
by johngg (Canon) on Sep 16, 2011 at 21:53 UTC | |
|
Re: Regexp help
by Anonymous Monk on Sep 16, 2011 at 21:10 UTC | |
by thewebsi (Scribe) on Sep 17, 2011 at 07:57 UTC |