Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, I have a question about inserting characters into strings. Before anyone says RTFAQ or some such, this is a bit different than the question or 2 I've found in the Q&A... I have an array of strings of text, mostly UPPERCASE, with intermittent lowercase html tags. I want to insert a space after every 10th UPPERCASE letter, and a newline (and/or html-br) after every 100th, regardless of how many other characters are interspersed between them. My first thought was something like:
@space = #some array of long text strings; $n = () = @space; $i = 0; while ($i < $n) { $space[$i] =~ s/([A-Z]{10}?)/$1 .' '/gxe; $i++; }
And that works great, when there are 10 UPPERCASE in a row, but not when there is any lowercase or brackets separating them. Then I tried some cocamamie bit where I was counting and incrementing after every instance of an uppercase, but I wound up trying to write to $1, which I know is read only. Can anyone enlighten me on a way to accomplish this? Thanks, Matt - -- Matt Dunn - mdunn@stwing.org http://www.stwing.org/~mdunn/

Replies are listed 'Best First'.
Re: Inserting characters into strings
by BrowserUk (Patriarch) on Jun 01, 2004 at 14:22 UTC
    #! perl -slw use strict; my @strings = map{ join'', map{ chr( rand(26) + ( rand() < .9 ? 65 : 97 ) ) } 1..1000 } 1 .. 20; print for @strings; for my $string ( @strings ) { $string =~ s[((?:[A-Z][^A-Z]*){10})][$1 ]g; $string =~ s[((?:[A-Z][^A-Z]*){100})][$1\n]g; } print $/, $/; print for @strings;

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: Inserting characters into strings
by borisz (Canon) on Jun 01, 2004 at 14:05 UTC
    $space[$i] =~ s/((?:[A-Z][^A-Z\n]*){10})/$1\n/gx;
    Boris
      Thanks Boris, I tossed in:
      $i = 0; while ($i < $n) { $space[$i] =~ s/((?:[A-Z][^A-Z\n]*){10})/$1 /gx; $space[$i] =~ s/((?:[A-Z][^A-Z\n]*){100})/$1 <br \/>/gx; $i++; }
      and it did the trick beautifully. Not exactly what you suggested, but almost. Thanks. -Matt