in reply to perl regex for xml

This is a case where there really is no good reason to run a shell command from within your perl script -- especially when the shell command is only going to run another perl script, as a one-liner. That's just way too complicated.

The easy way is to slurp the whole file into a scalar variable, do your regex substitution, and write the string back out to a file. (I'd recommend keeping the original as-is and saving the altered data to a different file, so you can be sure it worked before obliterating the original data.)

Here's one way to do your task:

#!/usr/bin/perl use strict; my $find = '(<!--\s*<control_link_address>push1\.mycompany\.com</contr +ol_link_address>\s*-->)'; my $rplc = '$1\n <control_link_address>mdp.travel.co.uk</control_link_ +address>\n'; open( IN, "<", "/tmp/ls.conf" ) or die "/tmp/ls.conf: $!"; $/ = undef; $_ = <IN>; eval "s{$find}{$rplc}"; open( OUT, ">", "/tmp/ls.conf.new" ) or die "/tmp/ls.conf.new: $!"; print OUT;
I'm using a string eval so that the "$1" will behave as intended. I'm sure there are better ways... (Parsing, maybe?)

Replies are listed 'Best First'.
Re^2: perl regex for xml
by equick (Acolyte) on Jun 20, 2010 at 08:44 UTC

    Hi graff,

    Thanks for the reply, that's a really clever bit of coding! I tried it out and it worked perfectly.

    Ed.