in reply to Tied scalars to emulate $&, $' and $` without global performance hit

Followup to my own post:

I just wanted to mention a couple of things that others have asked me about regarding this snippet:

First, the issue of these classes not working properly for the substitution ( s/// ) operator. If the size of the string changes, you're out of luck, and the classes will go looking in the wrong place for the prematch, postmatch, and match strings.

This is because I pass the string being matched against by reference, rather than by copy. I chose this strategy for efficiency's sake. Passing by reference is faster than copying a whole string (if the string is large), and more memory efficient. I also chose this strategy because it means that you only have to tie the scalars once. If the string being matched against gets changed in some way, you don't have to go and re-tie everything.

But this strategy runs amock if the string changes before you access the tied scalars to retrieve the match substrings. And the substitution operator does just that; it changes the string. Perl's default solution (aka, the $`, $&, and $' operators) is to copy the string before it gets changed. And once used one time, Perl automatically performs a string copy every time the regex engine is invoked. My solution doesn't do any copying.

You can emulate Perl's means of copying the string being matched, so that the s/// operator will work with these classes. The way to do that is to modify my snippet so that instead of passing the string by reference, it gets passed directly (in other words, a copy gets made).

This will fix the s/// problem, but will create more work for the user. It will mean that any time the string being matched changes in any way, the scalars will have to be untied and retied. That's a big pain.

At any rate, this was just a "what if" type of snippet. It's really not all that useful, but just another fun gadget for the bag-of-tricks (aka, the toolbox).

Oh, and the other thing I wanted to mention... the snippet could easily be made more robust by checking, and returning undef if @+, @- are undefined, if length $string is less than $+[0], or if the string is undefined. A simple patch, but where this is just something to play with, thorough error checking is less important than a clear example of the principles at work.

Now back to our scheduled programming, currently in progress... ;)


Dave

  • Comment on Re: Tied scalars to emulate $&, $' and $` without global performance hit