以下程序无效。我无法使用变量(用户输入)替换新单词
#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
答案 0 :(得分:3)
您需要使用s///
运算符而不是tr///
。
第一个意味着'替换':它用于替换文本的某些部分(由给定模式匹配)和其他文本。例如:
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'替换,'a'变成'o'并且't'变成'g'。很酷,对。 )
This part Perl文档将带来更多启示。 )
P.S。这是您的脚本的主要逻辑问题,但还有其他几个。
首先,您需要从输入字符串中删除结束符号(chomp
):否则该模式可能永远不会匹配。
其次,您应该在quotemeta
表达式的第一部分中使用\Q...\E
序列替换s///
调用,但是将其从第二部分中删除(因为我们将替换为 text < / em>,而非模式)。
最后,我强烈建议开始使用词汇变量而不是全局变量 - 并将它们声明为尽可能接近其使用位置。
所以它接近这个:
# 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";
答案 1 :(得分:0)
尝试以下方法:
$what = 'server'; # The word to be replaced
$with = 'file'; # Replacement
s/(?<=\${)$what(?=[^}]*})/$with/g;
答案 2 :(得分: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;