Search and replace between patterns.

I have the following xml on which I'm trying to replace the ip address of the employee Mark. I have written the script as
====================================================
#!/usr/bin/perl -w
use warnings;
use strict;

undef $/;
open FILEHD, 'test.xml' or die "Cannot open the file\n";
my $fileVar = <FILEHD>;
$/="\n";

my $emp="Mark";
my $prop="Emp.IP";
my $value="1.1.1.1";

$fileVar =~  s/(\b$emp.*?<$prop>)\b\S*.*\b(<.*Employee>\b)/$1$value$2/s;

print $fileVar;
=========================================================
But the ip address does not get replaced. I have tried different combinations but none works. Can you please suggest how it can be achieved.


==========================================================
        <Employees>
                <Employee id="17">
                        <Employee.Name>Mark</Employee.Name>
                        <Emp>
                                <Emp.IP>10.32.4.27</Emp.IP>
                                <Emp.Sal>5890</Emp.Sal>
                        </Emp>
                        <Last>
                                <Last.Community>public</Last.Community>
                                <Last.Sal>5896</Last.Sal>
                        </Last>
                </Employee>
                <Employee id="16">
                        <Employee.Name>Smith</Employee.Name>
                        <Emp>
                                <Emp.IP>10.32.4.25</Emp.IP>
                                <Emp.Sal>5890</Emp.Sal>
                        </Emp>
                        <Last>
                                <Last.Community>public</Last.Community>
                                <Last.Sal>5896</Last.Sal>
                </Employee>
           </Employees>
rohit_kapilAsked:
Who is Participating?
 
HonorGodConnect With a Mentor Software EngineerCommented:
$fileVar =~ s/\b($emp.*?<$prop>)\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.*?$prop\b)/$1$value$3/s;

would probably be better
0
 
HonorGodSoftware EngineerCommented:
#!/usr/bin/perl -w
use warnings;
use strict;

undef $/;
open FILEHD, 'test.xml' or die "Cannot open the file\n";
my $fileVar = <FILEHD>;
$/="\n";

my $emp="Mark";
my $prop="Emp.IP";
my $value="1.1.1.1";

$fileVar =~ s/\b($emp.*?<$prop>)\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(.*$prop\b)/$1$value$3/s;

print $fileVar;
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.