Reputation: 511
I have 2 lists, one is a list of files and the other is a logfile.
I want the if
query to print out every line of the logfile where a file from the list is named.
E.g.: list of files:
myfile1.txt
myfile2.txt
logfile:
line 1 html
line 2 filename="myfile2.txt"
line 3 /html
line 4 /xml
The desired output would be :
myfile2.txt found at line 2
I've tried several queries, such as
if(index($Lines_Logfile[$logcounter] ,'Lines_Name[$namecounter]') != -1);
or
if($Lines_Logfile[$logcounter] =~ m/$Lines_Name[$namecounter]/);
where $Lines_Logfile
and $Lines_Name
are the lists, and $namecounter
and $logcounter
are the lines of the for
loops.
Upvotes: 0
Views: 78
Reputation: 35208
You can use a regular expression. The trick is recognizing that you need to use quotemeta
or \Q...\E
to escape regex special characters, and word boundaries \b
to prevent matching a substring.
use strict;
use warnings;
use autodie;
my @files = qw(myfile1.txt myfile2.txt);
#open my $fh, '<', 'yourfile.log';
my $fh = \*DATA; # Testing data used for debug purposes
while (<$fh>) {
for my $file (@files) {
if (/\b\Q$file\E\b/) {
print "$file found at line $.: $_";
}
}
}
__DATA__
html
filename="myfile2.txt"
/html
/xml
Outputs:
myfile2.txt found at line 2: filename="myfile2.txt"
Upvotes: 3