Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Perl substitute with the nth match

by johngg (Canon)
on Jan 11, 2023 at 22:21 UTC ( [id://11149542]=note: print w/replies, xml ) Need Help??


in reply to Perl substitute with the nth match

Perhaps a programmatic pattern?

johngg@aleatico:~/perl/Monks$ perl -Mstrict -Mwarnings -E 'say q{}; my $text = <<__EOT__; cat dog cat mouse eel cat housecat catamaran fish __EOT__ my $n = 0; $text =~ s{cat(?{ $n++ })}{$n}g; say $text;' 1 dog 2 mouse eel 3 house4 5amaran fish

I hope this is helpful.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Perl substitute with the nth match
by haukex (Archbishop) on Jan 12, 2023 at 18:47 UTC

    Just to add a note to this: while it may work in this case, in the general case, one should be careful with assuming how often a (?{...}) gets called, as is stated at the top of its documentation.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2025-11-17 22:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (72 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.