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; } }