in reply to Problems with s///

Replace

foreach my $wild (@wilds) { $find =~ s/$wild/<font color=red>$wild<\/font>/; }

with

$find =~ s#([@wilds])#<font color=red>\1</font>#g;

Updated:

Sorry, I had to dash to a meeting and didn't have time to explain it.

First, about your chomp issue. It is having problems because your @solutions all end in a newline. Since that is not one of your specified letters, it gets pushed into the @wilds list. Chomping the input or explicitly not adding newlines to the @wilds list are the correct solutions. (cute trick: chomp @solutions; will chomp each element in the list at once, potentially saving you another loop)

Your version had two problems. It lacked the g at the end, which meant it only did the substitution for the first occurance of each wildcard found, and it didn't make all of the changes at once, so it could find wildcards inside of the text you were adding when it looped around for the next wildcard.

So anyway, here's how that works: The substitution looks for any character in the list [@wilds] (the square brackets -- denoting a "character class" -- tell it to match any element). It then remembers what it matched (the parentheses around the brackets -- called capturing parentheses -- tell it to do that). It then replaces that with a string made up of the opening tag, the character it just matched (denoted by the \1) and the closing tag. The g modifier at the end tells it to repeat this match against the entire original string. Lastly, I used the fact that you do not have to use / as your delimiter to avoid having to escape the / in your closing tag (s/// can also be written s### or s~~~ or many many other ways). (No doubt someone else will be able to point out all of my misconceptions and mistakes in the above, but I'm here to learn, too ... check out perlre for more info)


The intelligent reader will judge for himself. Without examining the facts fully and fairly, there is no way of knowing whether vox populi is really vox dei, or merely vox asinorum. — Cyrus H. Gordon

Replies are listed 'Best First'.
Re^2: Problems with s///
by sulfericacid (Deacon) on Jan 25, 2006 at 19:56 UTC
    Whoa there, idsfa!

    I made the said changes and it not only fixed the corrupted s///, but it also fixed it so duplicate letters as wilds are also working.

    I understand your code but I don't see how it's much different than my loop (just a tad shorter). So why does your code make everything work? What was my bug?

    Thanks much!



    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid