您需要使用的,而不是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";