in reply to regex: Need help substituting

If you have an other way of achieving the result I need, I'd be happy to learn about it.
In general, using an XML parser is preferable to using regular expressions. All parsers require an investment in time to learn, and XML::Twig is a good choice:
use warnings; use strict; use XML::Twig; my $x = '<map> <section1> <parameter>Some text</parameter> <rstate>CHANGE_THIS</rstate> </section1> <section2> <subsection> <parameter>dont change this</parameter> <rstate>CHANGE_THIS</rstate> </subsection> <subsection> <parameter>dont change this</parameter> <rstate>DONT CHANGE THIS</rstate> </subsection> <subsection> <parameter>dont change this</parameter> <rstate>CHANGE_THIS</rstate> </subsection> </section2> <section3> <parameter>dont change this</parameter> <rstate>DONT CHANGE THIS</rstate> </section3> </map> '; my $t = XML::Twig->new( twig_handlers => { rstate => \&rstate }, pretty_print => 'indented', ); $t->parse($x); $t->print(); sub rstate { my ($t, $rstate) = @_; my $text = $rstate->text(); $text =~ s/CHANGE_THIS/CHANGED/; $rstate->set_text($text); } __END__ <map> <section1> <parameter>Some text</parameter> <rstate>CHANGED</rstate> </section1> <section2> <subsection> <parameter>dont change this</parameter> <rstate>CHANGED</rstate> </subsection> <subsection> <parameter>dont change this</parameter> <rstate>DONT CHANGE THIS</rstate> </subsection> <subsection> <parameter>dont change this</parameter> <rstate>CHANGED</rstate> </subsection> </section2> <section3> <parameter>dont change this</parameter> <rstate>DONT CHANGE THIS</rstate> </section3> </map>

Replies are listed 'Best First'.
Re^2: regex: Need help substituting
by the_perl (Initiate) on Apr 07, 2012 at 14:20 UTC
    Thanks for your reply! That would work using the parser, given all values need to be changed are the same? If they differ I would need several instances of the parser? If I'm not mistaken the parser approach builds around the idea that I already know the value, which is not my case. I need to read the old value, do some calculations and reinsert the new value. I realize my example was not optimal, sorry for that. In reality all values are not neccecarily the same. I still would like to know how this would be achieved using regexp. Thanks again, Pontus

      You can do whatever calculations you like in the XML::Twig tag handler. Trying to do this with regexen is like hammering in a screw---you can do it but it's neither the easiest nor the most adequate way, so just don't.

      I realize my example was not optimal
      OK, so show us a better example of what you are trying to do, what you have tried, and how it doesn't work for you.