问题描述
我正在尝试使用“s/substring/replacement/”将子字符串替换为所有小写字母,以便进行全局搜索和不区分大小写的搜索。
读取文件:
while(<>){
print $_/XXX/book/i; #this line prints the default variable $_
}
样本输入:
I have a BOOK to read.
I like BoOk to read.
示例输出:
I have a book to read.
I like book to read.
我不确定使用“$_”的方式是对还是错。
解决方法
在 while(<>) {...}
循环中,主题变量 $_
包含当前行。如果您未指定要操作的字符串,则替换运算符 s///
默认使用此变量。试试下面的代码:
my $str = 'book';
while(<>){
s/(\Q$str\E)/lc $1/gei;
print;
}
-
注意:如果您不想替换另一个单词内的子字符串
book
,可以在正则表达式中添加单词边界\b
:s/\b(\Q$str\E)\b/lc $1/gei;
-
注意:使用双括号
<<>>
而不是<>
更安全,请参阅 perlop 了解更多详情。