# execute the command and save results in a file handle to reduce memory usage if (($head =~ /.+/) && ($tail =~ /.+/)) { my @lastLines = (); my $length; open (my $fh, $vars{cmd} . " 2>&1|") or die; while (<$fh>) { #$logger->info($fh . " " . $_); if ($_ =~ /$tail/ims) { #found the last line, terminate loop, do not append the output $tailFound = 1; last; } if($headFound){ #the header line is already found and ignored, so safe to apprend output $output .= $_; } if (!$headFound and $_ =~ /$head/ims) { #next lines will be the matched output $headFound = 1; } #keeps track of the most recent N lines push(@lastLines, $_); my $length = @lastLines; if($length >= $vars{lastNLines}){ shift(@lastLines); } #$output .= $_; } unless ($headFound && $tailFound) { $output = "\n\nCould not match command output. Printing the last $vars{lastNLines} lines:\n"; $output .= join("", @lastLines); } close ($fh); } else { open (my $fh, $vars{cmd} . " 2>&1|") or die; while (<$fh>) { #$logger->info($fh . " " . $_); $output .= $_; } close ($fh); }