Home: Perl Programming Help: Beginner:
perl \ query



aiyer100
New User

Mar 15, 2009, 8:56 PM


Views: 733
perl \ query

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


Views: 718
Re: [aiyer100] perl \ query

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


Views: 716
Re: [1arryb] perl \ query

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;

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