Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

replacing part of a string

by Anonymous Monk
on May 13, 2009 at 10:01 UTC ( [id://763709]=perlquestion: print w/replies, xml ) Need Help??

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

Hello Monks, I have a file which have following functions :
$A = B * C; $P = D+E+C;
Iwant to repalce "C" in these functions by $z i m not finding a way to do that, can any one give a solution!!! Thanks!!!

Replies are listed 'Best First'.
Re: replacing part of a string
by almut (Canon) on May 13, 2009 at 10:15 UTC
    I want to repalce "C" in these functions by $z

    Replace with a literal '$z':

    my @funcs = ( '$A = B * C;', '$P = D+E+C;' ); for my $func (@funcs) { $func =~ s/C/\$z/g; print "func : $func\n"; } __END__ func : $A = B * $z; func : $P = D+E+$z;

    Or, replace with the value of a variable $z:

    ... my $z = 99; for my $func (@funcs) { $func =~ s/C/$z/g; print "func : $func\n"; } __END__ func : $A = B * 99; func : $P = D+E+99;

    (Also note that, because $func is an alias to the original value, the values in @funcs would be modified here. If that's not intended, you'd have to make a copy of the value before doing the substitution...)

Re: replacing part of a string
by radiantmatrix (Parson) on May 13, 2009 at 15:48 UTC

    Hm, think about it this way:

    open my $FILE, '<', $name_of_file_with_functions_in_it or die ("Crap: +$!"); while (<$FILE>) { s/\bC\b/$z/g; # replace the *word* "C" with the contents of $z print $_; } close $FILE;

    This prints the output to STDOUT

    If you want to replace 'C' with the literal string '$z', then you just have to escape the $ in the above (\$z).

    <radiant.matrix>
    Ramblings and references
    “A positive attitude may not solve all your problems, but it will annoy enough people to make it worth the effort.” — Herm Albright
    I haven't found a problem yet that can't be solved by a well-placed trebuchet
      Hey!!! Its Working thanx!!! monks... :)
Re: replacing part of a string
by dHarry (Abbot) on May 13, 2009 at 10:05 UTC
    Use the tr operator or the substr function.

    Update
    My mistake, obviously the tr operator is not a good choice. The substr function or the s operator as suggested below both are fine.

      How would you do this with tr///?

        Good point, obviously I wouldn't;)

Log In?
Username:
Password:

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

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

    No recent polls found