I won't go into details here, but I want to iterate through every occurence of certain regexp in string and do mutilate it in various ways. Now, as long as the mutilation is only limited to area of matched regexp, I can just do

$hop =~ s/(r(eg)e(xp)/mutilate($1,$2)/eg
or something like that. Cool. But s///eg runs out of shots pretty quickly: what if I want to mutilate areas before or or after the match, for example, to kill areas between two matches? What if I want the mutilated result to go through s///eg mangle too? So, I figure, I'll go like:

while ($hop =~ m/r(eg)e(xp)/g) { // handle stuff // to replace, substr($hop,length $`,length $&) = $replace; and th +ink about slowness of $`, $& and all // to rewind, pos($hop)=$location; }

Now, I don't think we need do much benchmarks to see that the second version is slow as hell. What can I do about that? I realize $`, $& and calculating their lengths is incredibly slow, and I realize s/// has been optimized to do just that, but that doesn't help me a bit. Is there a way for s/// RHS to touch the output-string-in-build (I don't see any problems that could make)? Is there a way to know the location of LHS match in s/// RHS (again, I bet s/// already has this internally, didn't they just bother telling me?)? Any other suggestions?

P.S. Yes, this is related to my last Seek of Perl Wisdom. tilly, the approach you suggested I interpreted as way 2. If you didn't mean that, elaborate.


In reply to Why is while(m//g){} so much slower than s///eg and what can I do about it? by kaatunut

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.