http://www.perlmonks.org?node_id=1004858


in reply to Replace the nth occurence

I like your solution for replacing the nth occurrence of a character within a string. I don't know whether the following is a 'better suggestion,' but what about initializing $n (for the nth) to the desired occurrence:

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

Output:

a,b|c,d