ssr1012 ssr1012 - 8 months ago 90
Perl Question

Need to add an prefix based on the two arrays

I have two arrays @Mister and @Mrs and need to add prefix based on the values.

@Mister = qw(Parasuram Raghavan Srivatsan);
@Mrs = qw(Kalai Padmini Maha);

my $str = "I was invited the doctor Parasuram and Kalai and civil Engineer Raghavan and Padmini and finally Advocate Srivatsan and Maha";

#Mr. Parasuram Mr. Raghavan Mr. Srivatsan
if(grep ($_ eq $str), @Mister)
{ $str=~s/($_)/Mr. $1/g; }

#Mrs. Kalai Mrs. Padmini Mrs. Maha`
if(grep ($_ eq $str), @Mrs)
{ $str=~s/($_)/Mrs. $1/g; }

Output Should be:

I was invited the doctor Mr. Parasuram and Mrs. Kalai and civil Engineer Mr. Raghavan and Mrs. Padmini and finally Advocate Mr. Srivatsan and Mrs. Maha

Could someone simplify the way I am doing and whats wrong in this code.

Answer Source
my $mr_re  = join '|', @Mister;
my $mrs_re = join '|', @Mrs;

$str =~ s/($mr_re)/Mr. $1/g;
$str =~ s/($mrs_re)/Ms. $1/g;

(I used the neutral Ms above but if you are sure replace it for Mrs as in the question.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download