2012-09-04 70 views
0

以下程序無法正常工作。我使用變量(用戶輸入)如何將變量傳遞給PERL中的正則表達式

#Perl program that replace word with given word in the string 
$str="\nThe cat is on the tree"; 
print $str; 
print "\nEnter the word that want to replace"; 
$s1=<>; 
print $s1; 
print "\nEnter the new word for string"; 
$s2=<>; 
print $s2; 
$str=~ tr/quotemeta($s1)/quotemeta($s2)/; 
print $str 

回答

3

您需要使用的,而不是tr///s///運營商是無法與新詞來替換詞。

第一個意思是「替代」:它用於用某些其他文本替換文本的某些部分(由給定模式匹配)。例如:

my $x = 'cat sat on the wall'; 
$x =~ s/cat/dog/; 
print $x; # dog sat on the wall 

第二個意思是'音譯':它是用來替換一些範圍的符號與另一個範圍。

my $x = 'cat sat on the wall'; 
$x =~ tr/cat/dog/; 
print $x; # dog sog on ghe woll; 

這裏發生的是所有 'C' 是由 'd', '一個' 成爲 'O',並轉化到 'G' 'T' 置換。很酷,對。 )

This part的Perl文檔會帶來更多的啓發。 )

P.S.這是你的腳本的主要邏輯問題,但還有其他幾個。首先,您需要從輸入字符串中刪除末尾符號(chomp):否則該模式可能永遠不會匹配。

其次,你應該在s///表達的第一部分\Q...\E序列代替quotemeta電話,但是從第二乾脆放棄它(就像我們文字,而不是一個模式取代)。

最後,我強烈建議開始使用詞法變量而不是全局變量 - 並儘可能將它們聲明爲儘可能接近它們的使用位置。

因此變得接近這一點:

# these two directives would bring joy and happiness in your Perl life! 
use strict; 
use warnings; 

my $original = "\nThe cat is on the tree"; 
print $original; 

print "\nEnter the word that want to replace: "; 
chomp(my $word_to_replace = <>); 
print $word_to_replace, "\n"; 

print "\nEnter the new word for string: "; 
chomp(my $replacement = <>); 
print $replacement, "\n"; 

$original =~ s/\Q$word_to_replace\E/$replacement/; 
print "The result is:\n$original"; 
0

嘗試以下操作:

$what = 'server'; # The word to be replaced 
$with = 'file'; # Replacement 
s/(?<=\${)$what(?=[^}]*})/$with/g; 
0
#Perl program that replace word with given word in the string 
$str="\nThe cat is on the tree"; 
print $str; 
print "\nEnter the word that want to replace"; 
chomp($s1=<>); 
print $s1; 
print "\nEnter the new word for string"; 
chomp($s2=<>); 
print $s2; 
$str=~ s/\Q$s1\E/\Q$s2\E/; 
print $str; 
相關問題