繁体   English   中英

如何在PERL中将变量传递给正则表达式

[英]How to pass variable to regular expression in 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

您需要使用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”。 很酷,对。

Perl文档的这一部分将带来更多启示。

PS这是脚本的主要逻辑问题,但还有其他几个问题。

首先,您需要从输入字符串中删除末端符号( chomp ):否则该模式可能永远不会匹配。

其次,您应该在s///表达式的第一部分中用\\Q...\\E序列替换quotemeta调用,但是从第二部分中完全删除它(因为我们用text而不是pattern进行了替换)。

最后,我强烈建议开始使用词法变量,而不要使用全局变量-并声明它们尽可能靠近它们的使用位置。

因此它接近于此:

# 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";

请尝试以下操作:

$what = 'server'; # The word to be replaced
$with = 'file';   # Replacement
s/(?<=\${)$what(?=[^}]*})/$with/g;
#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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM