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

I have 8 common looking varibles and I need to check for them all in one line of a file to change the font color. But when I ran the following all it did was exactly what I told it to do. it replaced $red1 with $red1 when what I wanted it to do was replace $red1 with "black" and $red2 with "red".
for ($i = 1; $i < 9; $i++) { $_ =~ s/\$red$i/\$red$i/sg; + }

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How would I replace the string 'Red1' with $Red[1]?
by Anonymous Monk on Jun 29, 2000 at 17:50 UTC
    Use an array (or a hash). What you're trying to do now smells like symbolic refrences, which are just yicky (to use the technical term ) and make your code harder to write and maintain.

    You will also need to use the /e modifier (which causes Perl to eval the right-side as an expression).

    use strict; my @red; $red[1]='black'; $red[2]='red'; $line =~ s/\$red(\d)/$red[$1]/ge;
Re: How would I replace the string 'Red1' with $Red1?
by chipmunk (Parson) on Nov 28, 2000 at 03:19 UTC
    Actually, it is not necessary to use the /e modifier in the QandAEditors' substitution, because without /e the right-hand side of a substitution interpolates just like a double-quoted string.
    $line =~ s/\$red(\d)/$red[$1]/g;