in reply to replace nth occurrence of |

Here is an explanation of why your code works the way it does and how to make it do what you want (with minimal changes). Your 1st substitution attempt (pos1) is successful, as you've noted. So, you've replaced the 10th | with "pipe". Now, you again want to replace the 10th | with "pipe", not the 11th:
use warnings; use strict; while (my $row = <DATA>) { my $pos1 = 10; $row =~ s/(\|)/!--$pos1 ? ' pipe ' : $1/ge; my $pos2 = 10; $row =~ s/(\|)/!--$pos2 ? ' pipe ' : $1/ge; my $pos3 = 10; $row =~ s/(\|)/!--$pos3 ? ' pipe ' : $1/ge; chomp $row; print "$row\n"; } print "doneagain\n"; __DATA__ 1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|g|h|i

Outputs:

1|2|3|4|5|6|7|8|9|a pipe b pipe c pipe d|e|f|g|h|i doneagain

Replies are listed 'Best First'.
Re^2: replace nth occurrence of |
by perl197 (Novice) on Sep 24, 2014 at 17:29 UTC

    Thanks much as that solves my problem and gets me to where i need to be. I'll experiment with the single pass as well. Thanks again sir monks!