Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

How would I replace the string 'Red1' with $Red[1]?

by draco_iii (Acolyte)
on Jun 29, 2000 at 17:29 UTC ( [id://20361]=perlquestion: print w/replies, xml ) Need Help??

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;

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://20361]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-25 20:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found