Ajax has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks. So I have an xml file that looks like this:
<author order="4">
<name>
<given_name>G. Mileti</given_name>
<surname/>
</name>
</author>
Obviously, it would be better if the given name and the surname were within the correct tags. So, I ran this:

perl -i.xml -p -e "s#<given_name>(\w\.) (\w+)</given_name(>?)#<given_name>$1</given_name>\n<surname>$2</surname$3#ig"

However, that replaces the xml with: <author order="4">
<name>
<given_name></given_name>
<surname></surname>
<surname/>
</name>
</author>
I'm not concerned with the fact that there are two surname tags. I was planning on the cleaning up the second one anyway. I am concerned that it makes me lose data. The capturing groups don't appear to be capturing.
When I open the file in oXygen (an xml editor) and use its regular expression find and replace option: Find: <given_name>(\w\.) (\w+)</given_name>
Replace: <given_name>$1</given_name>
<surname>$2</surname>
That works. They are nearly the same code. The only difference being with the closing > on given_name in the perl code to account for the fact that for some reason XML::Simple thinks that having newlines before each closing > is a good idea.

Any help would be greatly appreciated.
  • Comment on Capturing Groups not Capturing for some reason

Replies are listed 'Best First'.
Re: Capturing Groups not Capturing for some reason
by Fletch (Bishop) on Jun 06, 2008 at 20:18 UTC

    You don't say what platform you're on, but many *NIX shells use $FOO to signify variable expansion and that works within double quotes (similar to how it works in Perl; go figure . . . :). Switch to single quotes (i.e. perl -i.xml -pe 's#<...#<given_name>$1...#ig' blah) and see if that doesn't stop your shell from drinking your milkshake expanding non-existent shell variables before Perl ever sees your -e code.

    Addendum: Not to </pedant> myself, but depending on the state of your shell at the time it expanded $1 etc you might have gotten rather stranger results; you just "lucked out" and managed to have no positional parameters ("unset" rather than "non-existent"; they're perfectly good shell variables that just happened not to have any content).

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      I knew it was something rediculously simple. Thanks. I'd tried everything but changing the quotes.