Doh! I didn't see your very similar solution before I posted....It is very similar, isn't it? And I hadn't seen yaphy's solution before I posted mine. Now, it left me wondering: is setting pos() necessary, or will Perl DWIM, and continue matching at the same point in the (original) string without help? That's what s///g does.
Well, it turns out that it appears to be using an offset in the string to keep track of where it was. So it is necessary.
Result: abXabXabXabXabXabxyabxyabxyabxyabxyabxyabxyabxyabxyabxyabxyabxy$_ = 'abxy' x 12; for(my $i = 0; m/ab/g and $i++<5;) { substr($_, $-[0], $+[0]-$-[0]) = 'abXab'; } print;
Not good.
Result: abXabxyabXabxyabXabxyabXabxyabXabxyabxyabxyabxyabxyabxyabxyabxy$_ = 'abxy' x 12; for(my $i = 0; m/ab/g and $i++<5;) { substr($_, $-[0], $+[0]-$-[0]) = 'abXab'; pos = $-[0]+5; } print;
Good.
p.s. I noticed this, which is also very awkward:
prints 2, not 5. What happened to the rule: the value of an assignment as an expression, is what you assign?my $length = length(substr($_, 2, 2) = 'abXab'); print $length;
In reply to Re: Re2: pattern matching a limited number of times
by bart
in thread pattern matching a limited number of times
by bob49
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |