0

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"/>
1
  • Please no XML libraries That's like saying "I need to drive a nail into this piece of wood - please don't suggest I use a hammer". Commented Aug 16, 2019 at 8:24

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.