Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Replace the nth occurence

by Kenosis (Priest)
on Nov 21, 2012 at 07:22 UTC ( #1004858=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Replace the nth occurence
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (12)
As of 2015-07-01 23:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (25 votes), past polls