Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable interpolation in LH regexp: s/$x/$hash{$x}/

Status
Not open for further replies.

platypus55

Programmer
Aug 15, 1999
32
0
0
US
I have this file, I want to substitute stuff into it and print it out.&nbsp;&nbsp;So I have this hash of all the stuff I want to substitute.&nbsp;&nbsp;The stuff I want to zap is the keys and the values are the stuff I want to substitute in for them.&nbsp;&nbsp;The test file has multiple occurrences of all the keys.<br><br>foreach $key (keys %myhash) {<br>&nbsp;&nbsp;if (/$key/) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s/$key/$myhash{$key}/;<br>&nbsp;&nbsp;}<br>}<br><br>But it doesn't change anything.&nbsp;&nbsp;How can I get it to EVALUATE $key?&nbsp;&nbsp;I'm a perl newbie so if you have a better way to do this thing I'm open to it.&nbsp;&nbsp;thank you.&nbsp;&nbsp;
 
That looks ok actually, presume you're wrapping it in code like this to process files from the command line and write to STDOUT?<br><FONT FACE=monospace><b><br>while(&lt;&gt;){<br>&nbsp;&nbsp;foreach $key (keys %myhash) {<br>&nbsp;&nbsp;&nbsp;&nbsp;if (/$key/) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s/$key/$myhash{$key}/;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;print;<br>}<br></font></b><br> <p>Mike<br><a href=mailto:michael.j.lacey@ntlworld.com>michael.j.lacey@ntlworld.com</a><br><a href= Cargill's Corporate Web Site</a><br>
 
1. You should quote escape symbols in search and replacement strings,<br>2. The if is obsolete because s handles it,<br>3. s needs the option g (global) to replace multiple instances of $key:<br><br>while(&lt;&gt;){<br>&nbsp;&nbsp;foreach $key (keys %myhash) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;s/\Q$key\E/\Q$myhash{$key}\E/g;<br>&nbsp;&nbsp;}<br>&nbsp;&nbsp;print;<br>}<br><br>Good luck<br>Thomas
 
Yep, the \Q did the trick.&nbsp;&nbsp;Learning PERL lied and said that using a $x would be variable interpolated but Programming PERL had the true skinny.&nbsp;&nbsp;Thanks VERY MUCH <br><br>It actually works without the \E so now I have to go look up in the book and see what that does.&nbsp;&nbsp;I thought the if was probably unnecessary too.&nbsp;&nbsp;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top