繁体   English   中英

如何在perl中的正则表达式中包含grep

[英]how to include grep in a regex in perl

所以我现在仍然坚持这个问题:1。我声明一个常量列表,比如说LIST 2.我想通读一个文件,我在while循环中逐行读取,如果该行有一个关键字列表,我打印线,或其他东西。

这就是我目前所拥有的:

use constant LIST => ('keyword1', 'keyword2', 'keyword3');
sub main{
    unless(open(MYFILE, $file_read)){die "Error\n"};
    while(<MYFILE>){
        my $line = $_;
        chomp($line);
        if($line =~ m//){#here is where i'm stuck, i want is if $line has either of the keywords
            print $line;
        }
    }
}

我该怎么做if if语句来匹配我想要程序做的事情? 如果没有$line变量并只使用$_我可以这样做吗? 我只使用$ line因为我认为grep会自动将LIST中的常量放入$_ 谢谢!

最简单的方法是将引用的正则表达式定义为常量而不是列表:

use strict;
use warnings;
use autodie;    # Will kill program on bad opens, closes, and writes
use feature qw(say);   # Better than "print" in most situations

use constant {
   LIST => qr/keyword1|keyword2|keyword3/, # Now a regular expression.
   FILE_READ => 'file.txt', # You're defining constants, make this one too.
};

open my $read_fh, "<", FILE_READ;  # Use scalars for file handles

# This isn't Java. You don't have to define "main" subroutine

while ( my $line = <$read_fh> ) {
    chomp $line;
    if ( $line =~ LIST ) {  #Now I can use the constant as a regex
        say $line;
    }
}
close $read_fh;

顺便说一句,如果你不使用autodie ,打开文件的标准方法如果没有打开则失败是使用or语法:

open my $fh, "<", $file_name or die qq(Can't open file "$file_name": $!);

如果必须使用列表作为常量,则可以使用join来生成正则表达式:

use constant LIST => qw( keyword1 keyword2 keyword3 );

...

my $regex = join "|", map LIST;
while ( my $line = <$file_fh> ) {
    chomp $line;
    if ( $line =~ /$regex/ ) {
        say $line;
    }
}

join采用一个列表(在本例中为常量列表),并用您给它的字符串或字符分隔每个成员。 我希望您的关键字不包含特殊的正则表达式字符。 否则,您需要引用这些特殊字符。


附录

我的$ regex =加入'|' => map + quotemeta,LIST; - 扎伊德

谢谢Zaid。 我以前不知道quotemeta命令。 我一直在用\\Q\\E尝试各种各样的东西,但它开始变得太复杂了。

另一种做Zaid的方法:

my @list = map { quotemeta } LIST;
my $regex = join "|", @list;

对于初学者来说, 地图有点难以理解。 map获取LIST每个元素并对其运行quotemeta命令。 这将返回我分配给@list 列表

想像:

use constant LIST => qw( periods.are special.characters in.regular.expressions );

当我跑:

my @list = map { quotemeta } LIST;

这将返回列表:

my @list = ( "periods\.are", "special\.characters", "in\.regular\.expressions" );

现在,句点是文字句点而不是正则表达式中的特殊字符。 当我跑:

my $regex = join "|", @list;

我明白了:

$regex = "periods\.are|special\.characters|in\.regular\.expressions";

这是一个有效的正则表达式。

暂无
暂无

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

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