in reply to Regex match and replace

$s = s/bar(?=bar)/foo/;

This statement does a substitution against the string held in the  $_ default scalar, and assigns to  $s the number of times a substitution occurred. As I do not know what, if anything, was in  $_ when you ran your code, it's hard to tell why the substitution failed (zero substitutions occurred). You may want a statement like
    $s =~ s/bar(?=bar)/foo/;
which can actually do a substitution on $s.

Input foofoo
Output foobar

I'm confused by this because you write that you want to replace some 'bar' in the input string with 'foo', but there ain't no 'bar' thar! Can you please clarify with exact input and desired output strings?

Update: Making some assumptions about what the input string might be, it's possible to do what you want using a positive look-behind:

c:\@Work\Perl>perl -wMstrict -le "my $s = 'barbar'; $s =~ s/(?<=bar)bar/foo/; print qq{'$s'}; " 'barfoo'
(substitute a 'bar' with 'foo' if it is preceded by a 'bar').


Give a man a fish:  <%-(-(-(-<

Replies are listed 'Best First'.
Re^2: Regex match and replace
by Anonymous Monk on Mar 04, 2015 at 22:26 UTC

    I see the problem that I had now, thanks for your answer.