2014-02-20 113 views
-3

下面是自我解釋:正則表達式替換不工作

管理>貓test.pl

#!/bin/perl 

$var1 = "SELECT * FROM CALENDAR WHERE CALNAME = (SELECT * from EMP))"; 
$var2 = "(SELECT * from EMP)"; 
$var3 = "zyx"; 

if ($var1 =~ /EMP/) 
{ 
    $var1 =~ s/$var2/$var3/; 
} 

print "var1=$var1\n"; 

管理> ./test.pl

var1=SELECT * FROM CALENDAR WHERE CALNAME = (SELECT * from EMP)) 

回答

2

你有$var2特殊字符作爲文字字符使用時應該quoted

$var1 =~ s/\Q$var2\E/$var3/; 
0

Comapre:

原創:

$var1 = "(SELECT * from EMP)"; 
$var2 = "abcd"; 

$var3 =~ s/$var1/$var2/; 

print "var1=$var1\n"; 
print "var2=$var2\n"; 
print "var3=$var3\n"; 

工作:

use strict; 
use warnings; 

my $var1 = "(SELECT * from EMP)"; 
my $var2 = "abcd"; 
my $var3 = "Something to keep, something to be replaced: (SELECT * from EMP)"; 
$var3 =~ s/\Q$var1\E/$var2/; 

print "var1=$var1\n"; 
print "var2=$var2\n"; 
print "var3=$var3\n"; 

輸出:

var1=(SELECT * from EMP) 
var2=abcd 
var3=Something to keep, something to be replaced: abcd 
+0

很抱歉,但只是發佈了正確的問題以上, – contravaluebets

+0

謝謝,你的建議工作。 Wondoering \ Q和\ E是什麼意思? – contravaluebets

+0

\ Q \ E之間的所有字符都是文字,您不必逃避它們。 – user1126070