Sam B
Sam B

Reputation: 27618

Perl append a substring with in a string

I am using perl and I want to append a substring with in a string.

what I have is this.

<users used_id="222" user_base="0" user_name="Mike" city="Chicago"/>
<users used_id="333" user_base="0" user_name="Jim Beans" city="Ann Arbor"/>

What I want is append word Mr. after the user name like this.

<users used_id="222" user_base="0" user_name="Mike, Mr" city="Chicago"/>
<users used_id="333" user_base="0" user_name="Jim Beans, Mr" city="Ann Arbor"/>

problem is I don't know how to do that? This is what I have so far. Please no XML libraries.

#!/usr/bin/perl

use strict;
use warnings;

print "\nPerl Starting ... \n\n"; 

while (my $recordLine =<DATA>) 
{
    chomp($recordLine);
    #print "$recordLine ...\n";

    if (index($recordLine, "user_name") != -1) 
    {
        #Found user_name tag ... now appeand Mr. after the name at the end ... how?
        $recordLine =~ s/user_name=".*?"/user_name=" Mr"/g; 
        print "recordLine: $recordLine ...\n";

    }
}

print "\nPerl End ... \n\n"; 

__DATA__
<users used_id="222" user_base="0" user_name="Mike" city="Chicago"/>
<users used_id="333" user_base="0" user_name="Jim Beans" city="Ann Arbor"/>

Upvotes: 0

Views: 109

Answers (1)

mob
mob

Reputation: 118665

You're almost there.

The .*? sequence in your regular expression stands for some characters in the original input, and you have to find a way to include those characters in the output, too.

That is done with a capture group in the pattern (enclosing part of the regular expression in parentheses) and a reference to $1 (meaning the contents of the first capture group) in the replacement pattern.

$recordLine =~ s/user_name="(.*?)"/user_name="$1, Mr"/g;

Upvotes: 3

Related Questions