use strict; use warnings; # Replace second comma my $n = 2; my $str = 'a,b,c,d'; $str =~ s/(,)/!--$n ? '|' : $1/ge; print $str;