Kleene’s Star: why does $_ = “a”; s/a*/e/g produce: ee

Your analysis of why the results are "ee" and "ebe" is completely accurate.

The “/g” modifier causes the regex to match once, and then try to match again from where the last match stopped.

The reason for the discrepancy (it doesn’t replace the empty string to the left of "a") is that is because "*" is greedy – it matches the MOST possible characters. From perldoc perlre :

By default, a quantified subpattern is “greedy”, that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match.

So it matches zero “a”s, and sees if it can match more. Since there are more “a”s in the string, it will match one more. Try to match more. None? Done. So we match the first “a”.

Then, “/g” causes us to try to match again (starting from where we stopped after last match completed), which now matches empty (zero “a”s) string.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)