String replacement in a file

Please support our Perl advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Feb 2005
Posts: 78
Reputation: nanodano is an unknown quantity at this point 
Solved Threads: 2
nanodano's Avatar
nanodano nanodano is offline Offline
Junior Poster in Training

String replacement in a file

 
0
  #1
Apr 4th, 2007
I have a very specific problem.

Does s/// work with strings that are contained in single quotes? I've been debugging and I'm trying to replace a string that contains a $ in it. If I use double quotes, it works for the string up until the $. If I use single quotes, it does not work with any string.

Here is my code; it involves file access, and file.data contains the string "testing $my string."

  1. #!/usr/bin/perl
  2.  
  3. $s1 = "testing $my string";
  4. $s2 = "testing $your string";
  5.  
  6. local ($^I, @ARGV) = ('.bak', 'file.data');
  7. while (<>) {
  8. s/$s1/$s2/g;
  9. print;
  10. }
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 898
Reputation: KevinADC has a spectacular aura about KevinADC has a spectacular aura about 
Solved Threads: 67
KevinADC's Avatar
KevinADC KevinADC is offline Offline
Practically a Posting Shark

Re: String replacement in a file

 
0
  #2
Apr 4th, 2007
  1. #!/usr/bin/perl
  2.  
  3. $s1 = "testing $my string";
  4. $s2 = "testing \$your string";
  5.  
  6. local ($^I, @ARGV) = ('.bak', 'file.data');
  7. while (<>) {
  8. s/\Q$s1\E/$s2/g;
  9. print;
  10. }
Reply With Quote Quick reply to this message  
Join Date: Feb 2005
Posts: 78
Reputation: nanodano is an unknown quantity at this point 
Solved Threads: 2
nanodano's Avatar
nanodano nanodano is offline Offline
Junior Poster in Training

Re: String replacement in a file

 
0
  #3
Apr 5th, 2007
I added an escape \ to $s1 like you did to $s2 and it worked great, thanks!
Reply With Quote Quick reply to this message  
Join Date: Mar 2006
Posts: 898
Reputation: KevinADC has a spectacular aura about KevinADC has a spectacular aura about 
Solved Threads: 67
KevinADC's Avatar
KevinADC KevinADC is offline Offline
Practically a Posting Shark

Re: String replacement in a file

 
0
  #4
Apr 5th, 2007
Ahh, now that I think about it \Q does not affect $ in a regexp, so you would use the quotemeta() function or add the escape character manually like you did.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 3979 | Replies: 3
Thread Tools Search this Thread



Tag cloud for Perl
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC