The regular expression in this code sample is designed to work on any line that begins with a tilde character, and in such a line, replace the first underscore with a plus sign.
It works exactly as expected, producing the output#!/usr/bin/perl while (<DATA>) { s/^ ~ .*? \K _ /+/x; print "$_"; } __DATA__ A line with an_underscore. A line with_two_underscores. ~A line with an_underscore starting with a tilde. ~A line with_two_underscores starting with a tilde.
That is, on the first tilde line, it replaces the only underscore with a plus, and on the second, it replaces only the first underscore, leaving the second one an underscore in the output.A line with an_underscore. A line with_two_underscores. ~A line with an+underscore starting with a tilde. ~A line with+two_underscores starting with a tilde.
To modify this code so that it changes all underscores in tilde lines to plus signs, the classic method is to add the /g option to the s// operator. But this doesn't work; it produces the same output as above, leaving the second underscore in the last line an underscore rather than changing it also to a plus sign as /g requests. What is going wrong?
In case the \K inside the regular expression was somehow inhibiting the /g option, I rewrote the substitution line to use a capture group instead:But this exhibits the same failure.s/( ^ ~ .*? ) _ /$1+/xg;
In reply to /g option not making s// find all matches by raygun
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |