Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re^2: Perl substitute with the nth match

by LanX (Saint)
on Jan 13, 2023 at 13:50 UTC ( [id://11149563]=note: print w/replies, xml ) Need Help??


in reply to Re: Perl substitute with the nth match
in thread Perl substitute with the nth match

> > OF COURSE I can do this in a loop.

> 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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11149563]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-26 00:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found