Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Answer: How do i find $a and replace it with $b when it's preceded by $c?

by btrott (Parson)
on Jun 13, 2000 at 22:31 UTC ( #17945=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > How do i find $a and replace it with $b when it's preceded by $c? - Answer contributed by btrott

<Editor's Note:>
Here is chromatic's post to which btrott is responding.

I prefer a simpler approach:

s/$c$a/$c$b/g; or s/($c)$a/$1$b/g;
Am I missing anything the lookbehind provides?

</Editor's Note>

All right... here's a benchmark of the two methods (lookbehind and just straight substitution). It looks like lookbehind is slightly faster, but not by a huge lot. Here's the code:

use Benchmark; use vars qw/$a $b $c/; ($a, $b, $c) = qw/bar baz foo/; timethese(shift || 1, { lookbehind => sub { local $_ = "foobarquux"; s/(?<=$c)$a/$b/g +}, chromatic => sub { local $_ = "foobarquux"; s/($c)$a/$1$b/g +}, });
And here are the benchmark results:
Benchmark: timing 500000 iterations of chromatic, lookbehind... chromatic: 15 wallclock secs (14.46 usr + 0.00 sys = 14.46 CPU) lookbehind: 13 wallclock secs (11.93 usr + 0.00 sys = 11.93 CPU)

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
[Corion]: Sane Dots Supplies - your brand manufacturer for satisfying experiences!
[choroba]: preparing the trip to Vietnam + buying a new car = enough fun
[Corion]: choroba: Yeah, that's a lot of "fun" for one week...
[Corion]: I guess I should stage some product photos for Sane Dots Supplies ;)
[marto]: I had some ideas about that Corion
[marto]: I'll send a message over the weekend maybe :P
[Corion]: choroba: I avoided the "fun" of emergency shopping for a new flat iron by trying the flat iron without the timer that sat between it and the mains power. Seems as if just the timer is broken.
[Corion]: marto: Heh, would be cool!

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (9)
As of 2017-01-20 10:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you watch meteor showers?




    Results (174 votes). Check out past polls.