Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

Re: Replace the nth occurence

by trizen (Hermit)
on Nov 21, 2012 at 10:56 UTC ( #1004895=note: print w/replies, xml ) Need Help??

in reply to Replace the nth occurence

A general solution:
my $nth = 4; my $str = 'a=>bb=>ccc=>dddd=>eeeee=>ffffff'; while ($str =~ /=>/g) { if (--$nth == 0) { substr($str, $-[0], $+[0] - $-[0], '~~|~~'); last; } } print "$str\n";

Replies are listed 'Best First'.
Re^2: Replace the nth occurence
by AnomalousMonk (Canon) on Nov 21, 2012 at 22:49 UTC

    In the sprit of this, also a generalized approach. No benchmarking done for two regexes used or versus other approaches. Note also that the index of the occurrence of the pattern which will be replaced is now zero-based. (Also: This approach could be generalized yet further by passing either a plain replacement string or a code reference. The string/reference could then be fed as appropriate to one of two  s/// substitutions, one without a /e regex modifier, one with. Code of a replacement reference would have access to all capture variables, etc.) All tests pass.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1004895]
erix looks for a red-herring joke but can't find one
Discipulus has worked physically and he rediscovered he is no more wont..
erix instead casts a baleful eye on another mysql q.
[Corion]: erix: I'm not sure if it really is MySQL - maybe MS SQL also has LIMIT 0
[erix]: it has TOP, IIRC
[Corion]: erix: Ah. I use where 1 = 0 for queries where I only am interested in the structure ;)

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (10)
As of 2017-01-23 09:27 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (192 votes). Check out past polls.