2012-09-04 62 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; 
相关问题