当我在Perl的match运算符中插入变量时,如何转义元字符? [英] How can I escape meta-characters when I interpolate a variable in Perl's match operator?

查看:117
本文介绍了当我在Perl的match运算符中插入变量时,如何转义元字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文件,其中包含要与之匹配的行:

Suppose I have a file containing lines I'm trying to match against:

foo
quux
bar

在我的代码中,我还有另一个数组:

In my code, I have another array:

foo
baz
quux

假设我们遍历文件,调用每个元素$word,然后检查要检查的内部列表@arr.

Let's say we iterate through the file, calling each element $word, and the internal list we are checking against, @arr.

if( grep {$_ =~ m/^$word$/i} @arr)

这可以正常工作,但是在文件中有一个fo.测试用例的情况下,.在正则表达式中用作通配符运算符,然后fo.然后匹配foo,这在某种程度上是可行的.这是不可接受的.

This works correctly, but in the somewhat possible case where we have an test case of fo. in the file, the . operates as a wildcard operator in the regex, and fo. then matches foo, which is not acceptable.

这当然是因为Perl将变量插值到正则表达式中.

This is of course because Perl is interpolating the variable into a regex.

问题:

如何强制Perl从字面上使用变量?

推荐答案

正确的答案是-不要使用正则表达式.我并不是说正则表达式是不好的,但是将它们用于(等同于)简单的相等性检查是过分的.

The correct answer is - don't use regexps. I'm not saying regexps are bad, but using them for (what equals to) simple equality check is overkill.

使用:grep { lc($_) eq lc($word) } @arr并开心.

这篇关于当我在Perl的match运算符中插入变量时,如何转义元字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆