为什么我的while循环似乎缺少一些匹配值? 读取文件后,此结果输出未返回所有可能的值。有一些缺失值。
# str_1,2,3,4 are my search strings
while ($line = <$fh>) {
if ( $line !~ /$str_1/ && $line =~ /$str_2/ ) {
open($fh, '>>report.txt');
print $fh "$file : $line";
close $fh;
}
if ( $line !~ /$str_3/ && $line =~ /$str_4/ ) {
open($fh, '>>report.txt');
print $fh "$file : $line";
close $fh;
}
}
输出:
Number of Attendance = 1 INFO:21
Number of Attendance = 2 INFO:21
Number of Attendance = 1 INFO:21
# There are results such as Number of Attendance = 8 INFO:21 which my code is not able to search.
例如:
#my log file which is the input
Number of Attendance = 1 from XYZ FACI INFO:21
Number of Attendance = 0 from UZQ BLAH INFO:21
Number of Attendance = 8 from WZW BLAH INFO:21
Number of Attendance = 0 from WZW BLAH INFO:21
Number of Attendance = 0 from WZW BLAH INFO:21
Number of Attendance = 0 from WZW BLAH INFO:21
so here my str1 = /Number of Attendance = 0/
str2 = /INFO:21/
#So output for my code now is only
Number of Attendance = 1 from XYZ FACI INFO:21
#But,Expected output should be
Number of Attendance = 1 from XYZ FACI INFO:21
Number of Attendance = 8 from WZW BLAH INFO:21
我认为它只读取我的所有文件一次并返回第一个输出值而不是返回所有可能的值。
答案 0 :(得分:1)
您正在关闭您尝试迭代的文件句柄!
如果您的代码中有use warnings;
,perl会警告您:
readline() on closed filehandle $fh at /home/felix/abdc/foo.pl line 9.
始终 use warnings;
和use strict;
像这样重写你的while循环:
open my $fh, "<$file" or die "Unable to open '$file' : $!";
open my $out, ">output_log" or die "Unable to open 'output_log' : $!";
while (my $line = <$fh>) {
if ( ... ) {
print $out $line;
}
...
}
close $out or die "Unable to finish writing output_log : $!";