CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
perl \ query

 



aiyer100
New User

Mar 15, 2009, 8:56 PM

Post #1 of 3 (476 views)
perl \ query Can't Post

I intend to write a perl code that goes someting like this:
$mytest1 = "\abc";
$myrep1 = "@\abc";
$mystring =~ s/$mytest1/$myrep1/g;

In other words, I need this to replace every occurence of \abc with @\abc.
I tried using $mytest1 = "\\abc";
but that does not seem to work..in fact it replaces even instances of "abc" with "@abc".
Any suggestions on how to do this one?
thx
Anand


1arryb
User

Mar 16, 2009, 10:44 AM

Post #2 of 3 (461 views)
Re: [aiyer100] perl \ query [In reply to] Can't Post

Hi aiyer,

You never initialize $mystring in your code snippet. Consequently,

Code
$mystring =~ s/$mytest1/$myrep1/g;

Will always fail. Not sure why you want the backslashes, but this:

Code
#!/usr/bin/perl 

use strict;
use warnings;

my $mytest1 = "\\\\abc"; # escape backslash twice: Once for the definition and once for the regex.
my $myrep1 = "@\\abc"; # escape backslash once for the regex.
my $mystring = "some string containing \\abc \\abc a couple of times"; # escape backslash once for the definition.

$mystring = ~s/$mytest1/$myrep1/g;

print "$mystring\n";

will print:

Code
some string containing @\abc @\abc a couple of times

Which is what you say you want. If not, it would help if you told us what these strings are and what they're for.

Cheers,

Larry


KevinR
Veteran


Mar 16, 2009, 11:05 AM

Post #3 of 3 (459 views)
Re: [1arryb] perl \ query [In reply to] Can't Post

All the escaping is not really necessary if using single-quotes and \Q...\E:


Code
#!/usr/bin/perl  

use strict;
use warnings;

my $mytest1 = '\abc'; # no escape necessary because of the single-quotes
my $myrep1 = '@\abc'; # same as above
my $mystring = '\abc \abc'; # no escapes because this is like input from a file

$mystring =~ s/\Q$mytest1\E/$myrep1/g; # \Q escapes the necessary meta characters

print $mystring;

-------------------------------------------------

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives