use strict; use warnings; my $data = <) { if ($line =~ m{ $a $b }xms) { for my $i (1 .. 2) { (my $c = $line) =~ s{ ($a $b) }{${1}_$i}xmsg; print $c; } } else { print $line; } } #### .abc_1(pqr) .abc_2(pqr) .abc_1(abc_1_p) .abc_2(abc_2_p)