in reply to Text parsing. Processing scopes and subscopes.

The best advice already given is use a template module. If you decide not to, I'd use substr rather than regular expressions

You can use index to find closing braces, the first one you find will be the close of the innermost scope. Then use the position you found with rindex to find the opening brace of that scope. You can extract the data with substr.

You can process the extract and then use substr to replace it and the braces in the original data.

Instead of processing the extract and replacing it, this snippet uses substr to replace the braces. This means you won't continually work on the same scope. It prints the bits it extracted as $extract so you can see it works on scopes in the correct order.

You need to make sure that whatever you substitute in doesn't have braces.

#!/usr/bin/perl use strict; use warnings; my $data = <DATA>; chomp $data; while () { my ($rpos, $lpos) = (0, 0); $rpos = index($data, "}", $rpos); last if $rpos < 0; $lpos = rindex($data, "{", $rpos); last if $lpos < 0; # $lpos + 1 so we don't extract the the { # -1 at the end to exclude the } my $extract = substr($data, $lpos + 1, $rpos - $lpos - 1); # get rid of these braces. substr($data, $lpos, 1) = "<"; substr($data, $rpos, 1) = ">"; # if you wanted to replace the entire section including braces # substr($data, $lpos, $rpos - $lpos + 1) = "<>"; print "|${extract}|\n"; } print "|${data}|\n"; __DATA__ text text {scope 4 text {scope 2 text {scope 1 text} scope 2 text} sco +pe 4 text {scope 3 text} scope 4 text } text text
Output
|scope 1 text| |scope 2 text <scope 1 text> scope 2 text| |scope 3 text| |scope 4 text <scope 2 text <scope 1 text> scope 2 text> scope 4 text +<scope 3 text> scope 4 text | |text text <scope 4 text <scope 2 text <scope 1 text> scope 2 text> sc +ope 4 text <scope 3 text> scope 4 text > text text|

Nuance