假设我有一个包含我想要匹配的行的文件:
foo
quux
bar
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我有另一个数组:
foo
baz
quux
Run Code Online (Sandbox Code Playgroud)
假设我们遍历文件,调用每个元素$word,以及我们正在检查的内部列表,@arr.
if( grep {$_ =~ m/^$word$/i} @arr)
Run Code Online (Sandbox Code Playgroud)
这样可以正常工作,但在某种可能的情况下,我们fo.在文件中有一个测试用例,它.在正则表达式中作为通配符操作符运行,fo.然后匹配foo,这是不可接受的.
这当然是因为Perl正在将变量插入到正则表达式中.
问题:
如何强制Perl按字面意思使用变量?
我正在使用Perl程序从文件中提取文本.我有一个字符串数组,我用它作为文本的分隔符,例如:
$pat = $arr[1] . '(.*?)' . $arr[2];
if ( $src =~ /$pat/ ) {
print $1;
}
Run Code Online (Sandbox Code Playgroud)
但是,数组中的两个字符串是$450和(Buy now).这些问题是字符串中的符号表示Perl正则表达式中的字符串结尾和捕获组,因此文本不会像我想要的那样解析.
有没有解决的办法?
$stuff = "d:/learning/perl/tmp.txt";
open STUFF, $stuff or die "Cannot open $stuff for read :$!";
while (<STUFF>) {
my($line) = $_; # Good practice to always strip the trailing
chomp($line);
my @values = split(' ', $line);
foreach my $val (@values) {
if ($val == 1){
print "1 found";
}
elsif ($val =~ /hello/){
print "hello found";
}
elsif ($val =~ /"/*"/){ # I don't know how to handle here.
print "/* found";
}
print "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
我的tmp.txt:
/* …Run Code Online (Sandbox Code Playgroud)