You could read file by "chunks" and not by lines
local $/ = "\n\n";
while(my $chunk = <LOG>) {
..
print("Just finished a chunk.\n");
}
Domanda
I am scanning a error log for the keyword "warning." When I find it, there is a particular case of warning that will end information relevant to the warning with only a newline character. What I want to do is scan through this error log, find the keyword warning keep skipping down the file until I find ONLY a newline character and then once I've found it, analyze that chunk and print it out.
The format would be something like this:
Warning! blah
blah
blah
orange
Warning! blah
blah
red
blah
Warning!
blah
blah
blah
yellow
Here's my code so far: use strict; use warnings;
my $file = $ARGV[0];
my $count = 0;
open(LOG, "<",$file) or die "cannot open < input: $!";
my $line = <LOG>;
while($line ne "")
{
if($line =~ /warning/i)
{
while($line !~/\A\n\z/)
{
if($line =~ /red/ || $line =~ /yellow/ ||$line =~ /black/)
{
$count++;
}
print($line);
$line = <LOG>;
}
print("Just finished a chunk.\n");
}
$line = <LOG>;
}
print($fix, "\n");
However, it's an infinite loop that constantly throws errors and I don't know why.
Soluzione
You could read file by "chunks" and not by lines
local $/ = "\n\n";
while(my $chunk = <LOG>) {
..
print("Just finished a chunk.\n");
}
Altri suggerimenti
You enter an infinite loop because when you reach the end of file and $line
is undefined, the expression
$line !~/\A\n\z/
is still true. You could try something like
...
while (defined($line) && $line !~ /\A\n\z/) {
...
instead.