Lets dissect this into smaller problems.
Simplification
I tried to simplify the case to avoid misunderstandings
DB<32> p "hello" =~ s/o*$/O/gr;
hellOO
DB<33> $_="hello"; s/o*$/O/g; print # for older Perls
hellOO
DB<34>
Surprise: the o is replaced twice.
Explanation so far
You and Hauke already explained that
- pos isn't changing after the first match b/c of the zero-width of $
- the empty o* is matching again °
(And I agree that the referenced perlre#Repeated-Patterns-Matching-a-Zero-length-Substring needs a rewrite)
DB<41> $_="hello"; say pos,"($1)" while m/(o*$)/g; # pos doesn't c
+hange
5(o)
5()
DB<42> p "hello" =~ s/x*$/O/gr; # empty match (
+no x)
helloO
Disappointments
Now, why is it surprising?
I think your case is that $ in combination with the /m modifier should act differently. Correct?
- Would this be consistent?
- Are there already examples of zero-width assertions who does it that way?
- Are there work-arounds to achieve what you want? (i.e. skipping zero-length matches)
Workarounds
Here a guess for the last question
DB<44> p "hello\nfoo" =~ s/o*\n/O/gmr;
hellOfoo
DB<45> p "hello\nfoo\n" =~ s/o*\n/O/gmr; # added \n at the end of
+ input
hellOfO
DB<46>
Meta
Question @all: Is the problem better understood now? :)
edit
added more code
update
added headlines for structuring
°) because empty patterns are always matching
compare
DB<59> p "12345" =~ s/x*/ /gmr;
1 2 3 4 5
DB<60>
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.