If $c is actually a pattern, you should use the lookbehind. If you're just dealing with strings, the fastest might be some work with substr/index.
use Benchmark; use vars qw/$a $b $c/; ($a, $b, $c) = qw/bar baz foo/; timethese(shift || 500000, { lookbehind => sub { local $_ = "foobarquux"; s/(?<=$c)$a/$b/g +}, chromatic => sub { local $_ = "foobarquux"; s/($c)$a/$1$b/g +}, chromatic2 => sub { local $_ = "foobarquux"; s/$c$a/$c$b/g }, substr => sub { local $_ = "foobarquux"; while ((my $p = index($_, "$c$a"))>=0) { substr($_, $p+length($c), length($a), $b); } }, });
Output:
chromatic: 11 wallclock secs (10.67 usr + 0.00 sys = 10.67 CPU) @ 46 +860.36/s (n=500000) chromatic2: 10 wallclock secs ( 8.81 usr + 0.00 sys = 8.81 CPU) @ 56 +753.69/s (n=500000) lookbehind: 10 wallclock secs ( 9.42 usr + 0.00 sys = 9.42 CPU) @ 53 +078.56/s (n=500000) substr: 4 wallclock secs ( 3.98 usr + 0.00 sys = 3.98 CPU) @ 12 +5628.14/s (n=500000)

In reply to Re: How do i find $a and replace it with $b when it's preceded by $c? by Roy Johnson
in thread How do i find $a and replace it with $b when it's preceded by $c? by whahoo

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.