简体   繁体   中英

perl print one output when matched a string

I am writing this simple code to get alert email when "error" found on my log.

The question is I want to get only one alert per scan my code is generate number of alert based number of error matched on the file.

open (LOG, "<$log") || die 'Could not OPEN log file';
while ($loglines = <LOG> ) {
if ($loglines =~ /Error/) { 
    print "Error on the log \n";
}
 }
 close (LOG);

the result looks like

Error on the log

Error on the log

Error on the log

Error on the log

Error on the log

Instead I want just one print "Error on the log" that i way I can get one email when error matched on the log file. What did I miss?

open my $LOG, "<", $log or die "Could not OPEN log file $log";
while (my $loglines = <$LOG>) {
  if ($loglines =~ /Error/) { 
   print "Error on the log\n";
   last;
  }
}
close($LOG);

There are a lot of improvements in that. The most important change is the addition of last; ; it terminates the loop on the first match.

Other changes are:

  • Use of lexical file handle.
  • Use of three-argument open.
  • Use of ' or ' instead of ' || '.
  • Local variable for $loglines (assuming you didn't need/use it elsewhere).
  • Error message identifies which file could not be opened (easier to debug!).
  • No trailing space on the printed message line.

Some would prefer a label added to the loop and then an explicit use of that in the last statement:

open my $LOG, "<", $log or die "Could not OPEN log file $log";
LOG_READER:
while (my $loglines = <$LOG>) {
  if ($loglines =~ /Error/) { 
   print "Error on the log\n";
   last LOG_READER;
  }
}
close($LOG);

I'm not convinced there is much gain here, assuming there are no enclosing loops. If there are any enclosing loops, then use the label.

I assume you are using:

use strict;
use warnings;

at the top of your script? If not, then do so. Perl experts use them to make sure they avoid making silly mistakes; Perl novices should use them for the same reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM