in reply to s/// only replacing most of the time...

I figured out what the main problem is.

Correct me if I'm wrong, but the s/// leaves off at the position just after the last replacement ($+[0]). So, if you have

$str = q{TTTTTTT}; $str =~ s/TTT/ttt/i;
the results is $str = tttTTTT But, if you throw a /g on the end of that, you'll have: $str = ttttttT

The problem I've been having is that rather than having s/// leave off at $+[0], I was assuming it left off at $-[0] + 1. The difference being, in the example above, with the /g included, the results would be:

$str = tttTTTT # after the first replacement $str = ttttTTT # after the second replacement .... $str = ttttttt # after all the global matches are said and done
This is what I had been hoping for.

So, my question becomes, is there a way to set s/// to start looking for replacements at $-[0] + 1 when in a global context, rather than at $+[0]

Replies are listed 'Best First'.
Re^2: s/// only replacing most of the time...
by blazar (Canon) on Jun 05, 2007 at 18:24 UTC
    $str = q{TTTTTTT}; $str = s/TTT/ttt/i;

    That should be =~.

    So, my question becomes, is there a way to set s/// to start looking for replacements at $-[0] + 1 when in a global context, rather than at $+[0]

    In Perl 6 it will be very easy, a matter of specifying the :ov (:overlap) modifier. In 5's realm you can play with the pos function. There's been a very recent discussion about these topics.

Re^2: s/// only replacing most of the time...
by suaveant (Parson) on Jun 06, 2007 at 03:23 UTC
    My last reply does that here... you use positive lookahead to match only one char in reality, then use the string length you are matching to get the right hand position. You could also do it by using \G and pos, but I wouldn't suggest it. The positive lookahead works well with these fixed length string matches.

                    - Ant
                    - Some of my best work - (1 2 3)