http://www.perlmonks.org?node_id=585927


in reply to Re: Efficient file handling (was Re^3: trouble parsing log file...)
in thread trouble parsing log file...

First and foremost, your line:

my @logfile=<LOG>;    # throw logfile into an array

does exactly what the comment says: it reads the whole logfile into an array (which you subsequently never use). That means that the test in the following line:

while ( <LOG> ) {

can never be true: the filehandle has already reached the end of the file by the time this line is reached. Just get rid of the first of these two lines.

However, once this problem is fixed, it becomes clear that your program logic is flawed. The program will only ever read just one line from the logfile, because all the branches of the if/elsif/else structure end with last. So if the first line of the logfile contains, say, just "foo", it will print a green button and stop executing, even if the second (or third...) line is "SERVER DOWN".

Lastly, as your regexes stand, $error will match eg "Downing Street", which is probably not what you want.

I suggest that you use something like the following (simplified for the purposes of this posting to read from __DATA__ rather from a filehandle, and to output a simple string):

use strict; use warnings; my $error = 'DOWN'; my $warn = 'PROBLEM'; my $redbutton = 'RED BUTTON'; my $greenbutton = 'GREEN BUTTON'; my $yellowbutton = 'YELLOW BUTTON'; my $button = $greenbutton; while ( <DATA> ) { if ( /\b$error\b/i ) { $button = $redbutton; last; } elsif ( /\b$warn\b/i ) { $button = $yellowbutton; } } print $button; __DATA__ foo tony.blair@downingstreet.gov.uk Watership Down bar