|Syntactic Confectionery Delight|
Re: CUFP: Random tag insertionby Roy Johnson (Monsignor)
|on Nov 25, 2003 at 18:39 UTC||Need Help??|
Your main loop had a couple of features that struck me as odd: the anchoring of the pattern, and the destruction of one string to build another. The if structure also had redundant branching (you're either going to tag or you're not, so you only need one if).
In pondering how I'd do it, I discovered why you destroy the string and create a new one: walking through the string and changing it becomes complicated. You end up getting lost. (The anchor and the if-structure points are still valid.)
By working from the end of the string, and indexing from the front (or vice-versa), you can insert into the string and not lose your place. A c-style for loop is handy for this:
Another technique that came to mind is the one-line main loop:
Trying to use a while(/\S/g) gets very messy. I was not able to work it out.
Then I started thinking about randomly opening and closing the tag, so you don't end up having to clean up closes followed immediately by opens.
With a toggle, you're always going to get about 50% of the characters tagged; the random number just determines how often you go from tagged to untagged. We need to walk forward through the string, so we'll index from the end:
Have you ever appended to substr()? I haven't, before, but it works.
The PerlMonk tr/// Advocate