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

I would like to take the non-blank chars in a text and convert them into dots, with the exception of the non-breaking-space pre tab. There may be more than one pre tab in the text. I can do this with one pre tab, but I can't figure out how to extend to more than one. Please help!
$text = "test of  this # ? my 0923 5834t674"; .... .. .......... . . .. .... ........

Here's the code that works with one pre tab.
if ($text =~ $nbsp) { $text =~ s/(.*)$nbsp(.*)//g; # ( ) PUTS TEXT INTO $1, $2, etc. $tex1 = $1; # WHAT COMES BEFORE THE PRE TAG $tex2 = $2; # WHAT COMES AFTER $tex1 =~ s/[^ ]/$repl/g; # BLANK OUT, EXCLUDING SPACES $tex2 =~ s/[^ ]/$repl/g; $text = "$tex1$nbsp$tex2"; } else { $text =~ s/[^ ]/$repl/g; } print "$text\n";


THANKS!

Replies are listed 'Best First'.
Re: Blanks with pre tag exceptions
by graff (Chancellor) on Mar 05, 2004 at 05:32 UTC
    $text =~ s/(.*)$nbsp(.*)//g; # this is your problem
    That regex will isolate exactly one occurrence of " " per line within $text, and will ignore all other occurences of pattern on the same line -- in fact, the logic of the initial ".*" wildcard match will consume all but the last " ".

    Maybe you want something like this:

    $text = "test of  this # ? my 0923 5834t674"; $text =~ s{(.*?)(\ )?}{($x=$1)=~tr/ /./c; "$x$2"}ge; print "$text\n"; __OUTPUT__ .... ..  .... . . .. .... ........
    Note that this executes a "tr///" within the replacement part of the s{}{} regex, to change the non-space characters to dots; it applies equally to all lines, whether they have "nbsp" in them or not (and for lines that do have nbsp, it applies to each occurrence in succession, as well as the portion of the line that follows that last nbsp, if any).
Re: Blanks with pre tag exceptions
by bart (Canon) on Mar 05, 2004 at 08:52 UTC
    Try:
    $text =~ s/( )|\S/$1 || "."/ge;
    This is my old "replace what you don't want replaced by itself, and anything else by whatever you want there instead" trick.