[英]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.