http://www.perlmonks.org?node_id=11121071


in reply to Regex replace leaking memory.

When perl does a match, it takes a copy of the original string (and a list of indices of where $1, $& etc matched) so that if $1 or $& etc are used later within the current scope, their value can be constructed on demand (the $1 etc variables are effectively tied). This extra SV is stored along with the regex object. I suspect in this case Devel::Leak is wrong.

Note that the copy uses copy-on-write, which allows multiple string SVs to share the same string buffer. In your case, the constant string "TESTING STRING" is shared with $string when the latter is assigned to. When the match is done, the string becomes shared for a second time. When the substitution is then done, $string is modified and its string buffer becomes unshared. This leaves the original buffer shared by the constant SV and the SV in the regex. I think the regex's SV is the one being displayed by Devel::Leak.

Over various releases, perl has differed in how it manages the copy kept by the regex; in particular, when the pattern itself had no captures and $& hadn't yet been seen during compilation perl used to overly-optimise by not capturing, and eval '$&' could return garbage.

Dave.