【发布时间】:2017-01-10 15:14:03
【问题描述】:
我有一个 Perl 程序,用户在其中输入一些文本、搜索模式和替换字符串。
我正在使用s/// 运算符将搜索模式替换为替换字符串,但在这种情况下,如果用户输入捕获变量(如$1)或反斜杠转义(如\u 或@987654326 @) 在替换字符串中,替换模式应该处理这些元字符,而是将它们视为字符串字符。
我有以下代码:
#!/usr/bin/perl -w
use strict;
chomp(my $text = <STDIN>); #read the text
chomp(my $regex = <STDIN>); #read the search pattern
chomp(my $replace = <STDIN>); #read the replacement pattern
$text=~s/$regex/$replace/g; # do replacement
print $text,"\n";
此代码的示例输入是
fred flintstone and wilma flintstone are good couples
(fred|wilma) flintstone
\u\L$1\E Flintstone
上面代码的输出是
\u\L$1\E Flintstone and \u\L$1\E Flintstone are good couples
我在下面的代码中找到了一种纠正方法:
#!/usr/bin/perl -w
use strict;
chomp(my $text = <STDIN>);
chomp(my $regex = <STDIN>);
chomp(my $replace = <STDIN>);
$replace = '"' . $replace . '"'; # creating the string as '"\u\L$1\E Flintstone"'
$text = ~s/$regex/$replace/gee; # applying double evaluation
print $text,"\n";
现在这段代码给出了正确的输出
Fred Flintstone and Wilma Flintstone are good couples
我想知道是否有更好的方法来解决这个问题?
【问题讨论】:
-
不,我认为没有更好的方法。您必须使用
s///中的评估选项。但请注意,如果您不信任用户,这可能会很危险。