Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Text parsing. Processing scopes and subscopes.

by nuance (Hermit)
on Aug 26, 2015 at 13:35 UTC ( [id://1140020]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1140020]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-25 14:18 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found