Another way:

my $nth = 3; my $rep = 1; my $chr = 'e'; my $str = "Terence and Philip are sweet\n"; my $pos = 0; $pos = index($str, $chr, $pos+1) for(1..$nth); substr($str, $pos) =~ s/$chr/$rep/g; print $str;

You could, of course, move the $pos finding part into a do block within the substr expression but it's a bit unwieldy.

Update: Well, my method's a little bit more wordy then quent's but it's ever-so-slightly faster, almost definately because it avoids doing the string-eval. I don't think it's a significant difference, though. I was just curious. :-)

my $s = "Terence and Philip are sweet\n"; my $c = 'e'; my $r = 1; my $n = 3; sub mine { my ($str, $chr, $rep, $nth) = @_; my $pos = 0; $pos = index($str, $chr, $pos+1) for(1..$nth); substr($str, $pos) =~ s/$chr/$rep/g; return $str; } sub quents { my ($str, $chr, $rep, $nth) = @_; my $i = 1; $str =~ s/($chr)/$i++<$nth?$1:$rep/eg; return $str; } use Benchmark qw( timethese cmpthese ); cmpthese(500000, { "Mine" => sub { mine ($s, $c, $r, $n) }, "Quent's" => sub { quents ($s, $c, $r, $n) }, }); __END__ Benchmark: timing 500000 iterations of Mine, Quent's... Mine: 14 wallclock secs (14.08 usr + 0.00 sys = 14.08 CPU) @ 35 +511.36/s (n=500000) Quent's: 19 wallclock secs (18.58 usr + 0.03 sys = 18.61 CPU) @ 26 +867.28/s (n=500000) Rate Quent's Mine Quent's 26867/s -- -24% Mine 35511/s 32% --

bbfu
Seasons don't fear The Reaper.
Nor do the wind, the sun, and the rain.
We can be like they are.


In reply to (bbfu) (another way) Re: Replacing a given character starting with the xth occurence in a string by bbfu
in thread Replacing a given character starting with the xth occurence in a string by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.