HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Replacing XML tag values

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
valuestagreplacingxml

Problem

This function replaces some XML tag values. The tags appear in the XML exactly once.I want to know if this can be done in a better way.

sub editConnConfig{
my ($DOMAIN,$rscDir,$walletDir,$DEFAULTPORT)=@_;
`perl -pi -e 's!.*?!$walletDir/fctrust.jks!sg' "$rscDir/ConnectionConfig.xml" 2>&1`;
`perl -pi -e 's!.*?!$walletDir/fckey.jks!sg' "$rscDir/ConnectionConfig.xml"`;
`perl -pi -e 's!.*?!jkspass1!sg' "$rscDir/ConnectionConfig.xml"`;
`perl -pi -e 's!.*?!$DOMAIN!sg' "$rscDir/ConnectionConfig.xml"`;
`perl -pi -e 's!.*?!$DEFAULTPORT!sg' "$rscDir/ConnectionConfig.xml"`;
}

Solution

First and foremost, XML is not a regular language, and therefore parsing it using regular expressions is not appropriate, and is asking for trouble.

Secondly, invoking perl within perl is clearly an awful idea. Invoking it multiple times is even worse.

As all the s!!! operations are performed on the same file, you could perform all of them at once in the same process, by separating them with semicolons, that is:

perl -pi -e 's!pattern1!replacement1!sg; s!pattern2!replacement2!sg' file


But as I said earlier, you should not call perl from within a perl function in a backtick expansion, but implement properly the operations (open file, read buffer, perform replacements, overwrite the file).

And instead of doing this using regular expressions, consider using an XML parser.

Code Snippets

perl -pi -e 's!pattern1!replacement1!sg; s!pattern2!replacement2!sg' file

Context

StackExchange Code Review Q#122718, answer score: 7

Revisions (0)

No revisions yet.