Sang.P Sang.P - 6 months ago 12
Perl Question

Perl Loop not filtering right results

Why does my while loop seem to be missing some match values?
This result output is not returning all the possible values after reading the files. There are some missing values.

# 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;
}
}


output:

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.


For example:

#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


I think its only reading all my files only once and returning the first output value instead of returning all the possible values.

Answer

You are closing the filehandle that you are trying to iterate over!

If you had use warnings; in your code, perl would have warned you:

readline() on closed filehandle $fh at /home/felix/abdc/foo.pl line 9.

Always use warnings; and use strict;

Rewrite your while loop like this:

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 : $!";
Comments