I am trying to look for a pattern in files and perform an operation if the pattern is found. The pattern is class <class_name> extends
. But I want to exclude the case in which I encounter the pattern //class <class_name> extends
ie I want to skip the operation when I get commented lines.
open my $fh, "<", $file_t or die "can't read open '$file_t': $OS_ERROR"; # Opening the file
while (<$fh>) {
if(/class\s{1,10}<class_name>\s{1,10}extends/){
#Perform the operation if we find above pattern
}
close $fh or die "can't read close '$file_t': $OS_ERROR"; #Closing the file
}
How do I include the piece of code to exclude the pattern I mentioned. Thanks for the help.
***********Edits************
I think I have to re-frame my question. I also want to ensure that when I look for class <class_name> extends
I should look for that pattern only and not if that pattern exists along with a //
before it. Something like, doing a "if and only if" that particular pattern exists with no other combination of characters.
如果您需要在同一个Regex表达式中包含检查(而不是将两个与and
绑定在一起,则可以使用负前瞻:
if (m{/^(?:(?!//).)*class\s{1,10}$className\s{1,10}extends}) {
One solution is to only allow whitespace before the definition (if classes can declared in indented scopes)
/^\s*class\s+<class_name>\s+extends/
Explanation
^ Start of line
\s* 0 or more whitespace characters
I think I found a solution with the help of above comments. I included the below line of code in my code: if(/^\\s*\\/\\/class\\s{1,10}<class_name>\\s{1,10}extends/){next;}
The new piece of code looks like this:
open my $fh, "<", $file_t or die "can't read open '$file_t': $OS_ERROR"; # Opening the file
while (<$fh>) {
if(/^\s*\/\/class\s{1,10}<class_name>\s{1,10}extends/){next;}
elsif(/class\s{1,10}<class_name>\s{1,10}extends/){
#Perform the operation if we find above pattern
}
close $fh or die "can't read close '$file_t': $OS_ERROR"; #Closing the file
}
Thanks for the help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.