Your specification and your code don't match up very well. You say you want to look for 'Response Queue Size:' followed by a number, and then to print something if that number is not zero. What your code is actually doing is printing whether or not that specific string is found. If the string isn't found, your code gives the same message as if it is present with a different number.
This will slurp the whole file, which is fine for small files. It will tell you if the string is not found or if the number is not zero.:
my $fn = 'C:/Users/katragas/Desktop/apadmin_get_status_log.txt';
open my $my_file, '<', $fn or die "Cannot open $fn: $!\n";
$/ = \0;
$_ = <$my_file>;
close $my_file;
if ( /Response Queue Size: (\d+)/ ) {
my $size = $1;
print "size: $size\n" if $size ne '0';
} else {
print "'Response Queue Size' not found.\n";
}
This will read the file line by line, which will save memory for larger files. It will tell you if the queue size is non-zero at the time it is found, and will tell you a total number of matches for 'Response Queue Size:' at the very end.
my $fn = 'C:/Users/katragas/Desktop/apadmin_get_status_log.txt';
open my $my_file, '<', $fn or die "Cannot open $fn: $!\n";
my $found = 0;
while ( <$my_file> ) {
if ( /Response Queue Size: (\d+)/ ) {
$found++;
my $size = $1;
print "\nsize: $size\n" if $size ne '0';
}
}
print "'Response Queue Size' found $found times\n";
close $my_file;
In neither of the above is it necessary to close the file handle since there's not much left to do after the read. However, the close illustrates where the file is no longer needed in each.
I've introduced error handling for not being able to open the file. I've also switched to three-argument open which is better for anything longer than a one-liner. I've also switched to lexical file handles rather than barewords.
Perl is more than a fancy wrapper around regular expressions. The capture and ne test are more natural to the problem than trying to solve the whole thing as a regex.
Update: used my to make $my_file a lexical as touched on by Laurent_R
|