[英]Perl: How do I search a text file line by line to find a specific pattern?
I want to find a string STRING
at the beginning of each line of a text file. 我想在文本文件每一行的开头找到一个字符串STRING
。 So far, I have: 到目前为止,我有:
open(FILEHANDLE, "sample.txt")
while(my $line = <$FILEHANDLE>){
if($line =~ PATTERN){
doSomething();
}
}
My question is: what do I put for PATTERN
that will make my code work? 我的问题是:我应该为PATTERN
放置什么以使代码正常工作? I know that STRING
will be at the beginning of each line of the text file, and that STRING
will be followed by whitespace. 我知道STRING
将会在文本文件每一行的开头,并且STRING
后面将是空格。 STRING
may change so it must be in a variable and not hardcoded in. STRING
可能会更改,因此它必须在变量中且不能进行硬编码。
So far, I can only think of the Python way to do this: 到目前为止,我只能想到使用Python的方式:
PATTERN = r"^" + re.escape(STRING) + r"\s"
if re.search(PATTERN, line):
doSomething();
How do I translate this to Perl? 如何将其翻译为Perl?
Also, if this is bad Perl syntax, please let me know so I can fix it. 另外,如果这是错误的Perl语法,请告诉我,以便对其进行修复。
You were almost there, just need to know that .
您快要在那里了,只需要知道这一点即可.
is string concatenation, not +
. 是字符串连接,不是+
。 and that quotemeta() does string escaping. 并且那个quotemeta()确实进行了字符串转义。
my $pat = "^".quotemeta($string)."\s" ;
while(my $line = <$FILEHANDLE>){
if($line =~ /$pat/){
doSomething();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.