简体   繁体   English

如何在不使用Perl中的正则表达式的情况下在文件中找到特定行?

[英]How can I find a specific line in a file without using regular expressions in Perl?

I have a file that I want to read in using the File::Slurp module then search that file for a specific line. 我有一个文件,我想使用File :: Slurp模块读取,然后搜索该文件的特定行。 I know Perl has regular expressions but the strings I'm searching for are user-generated so don't want to have to worry about escaping everything. 我知道Perl有正则表达式,但我正在搜索的字符串是用户生成的,所以不要担心逃避一切。 I could write a foreach loop to do this but was wondering if there's a function in Perl that will do this for me? 我可以编写一个foreach循环来执行此操作但是想知道Perl中是否有一个函数可以为我执行此操作? Everything I see online about finding text in Perl uses regular expressions. 我在网上看到的关于在Perl中查找文本的一切都使用正则表达式。

You can just use a regular expression. 你可以使用正则表达式。 You don't have to worry about escaping everything, Perl has the quotemeta function for that (or alternatively, "\\Q\\E"). 你不必担心逃避一切,Perl有这个的quotemeta函数(或者“\\ Q \\ E”)。

Like this? 像这样?

use List::Util qw<first>;

my $line 
    = first { index( $_, $something_users_are_looking_for ) > -1 } 
      <$file>
    ;

And if you want 'em all. 如果你想要他们所有人。

my @lines
    = grep { index( $_, $something_users_are_looking_for ) > -1 } 
      <$file>
    ;

你能用q()来使用字符串文字吗?

print(q(This string can contain regex: (\n\t*\n)(\n)));

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

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