> s/cat/++$i/ge
interestingly it's possible to avoid /e in an efficient inside-out (TIMTOW) loop version of m///
say pos($txt) while $txt =~ m/cat/g
Now with s/// this kind of works, but isn't efficient because pos will be reset each time
use v5.12; use warnings; use Data::Dump qw/pp dd/; my $txt = <<'___'; cat dog cat mouse eel cat housecat catamaran fish ___ say 'm-pos:', pos($txt) while $txt =~ m/cat/g; my $cnt=1; while ($txt =~ s(cat)($cnt)x) { say "s-pos:", pos($txt) // "undefined"; $cnt++; } say $txt;
m-pos:3 m-pos:11 m-pos:25 m-pos:34 m-pos:38 s-pos:undefined s-pos:undefined s-pos:undefined s-pos:undefined s-pos:undefined 1 dog 2 mouse eel 3 house4 5amaran fish
and no, using s///g would do the outer loop only once, tho there might be a way to force a single replace with (?FAIL) ... probably?
Cheers Rolf
(addicted to the 𐍀𐌴𐍂𐌻 Programming Language :)
Wikisyntax for the Monastery
In reply to Re^2: Perl substitute with the nth match
by LanX
in thread Perl substitute with the nth match
by misterperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |