943,724 Members | Top Members by Rank

Ad:
  • Perl Discussion Thread
  • Unsolved
  • Views: 4680
  • Perl RSS
Apr 4th, 2007
0

String replacement in a file

Expand Post »
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."

Perl Syntax (Toggle Plain Text)
  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. }
Similar Threads
Reputation Points: 36
Solved Threads: 2
Junior Poster in Training
nanodano is offline Offline
78 posts
since Feb 2005
Apr 4th, 2007
0

Re: String replacement in a file

Perl Syntax (Toggle Plain Text)
  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. }
Reputation Points: 246
Solved Threads: 67
Practically a Posting Shark
KevinADC is offline Offline
898 posts
since Mar 2006
Apr 5th, 2007
0

Re: String replacement in a file

I added an escape \ to $s1 like you did to $s2 and it worked great, thanks!
Reputation Points: 36
Solved Threads: 2
Junior Poster in Training
nanodano is offline Offline
78 posts
since Feb 2005
Apr 5th, 2007
0

Re: String replacement in a file

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.
Reputation Points: 246
Solved Threads: 67
Practically a Posting Shark
KevinADC is offline Offline
898 posts
since Mar 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Perl Forum Timeline: hi i have prob solve it plz
Next Thread in Perl Forum Timeline: Multiple scripts in one file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC