我如何才能等到将某些内容写入我的 perl 脚本中的日志文件

How can i wait until something is written to log file in my perl script

我实际上是在监视用于创建新文件(.log 文件)的目录,这些文件是由某些工具生成的,工具会在创建同一文件一段时间后写入日志条目,在此期间文件将为空.

以及我如何才能等到将某些内容写入日志以及基于日志条目的原因我将调用不同的脚本!,

use strict;
use warnings;
use File::Monitor;
use File::Basename;
my $script1 = "~/Desktop/parser1.pl";
my $scrip2t = "~/Desktop/parser2.pl";
my $dir = "~/Desktop/tool/logs";
sub textfile_notifier {
my ($watch_name, $event, $change) = @_; 

my @new_file_paths = $change->files_created; #The change object has a property called files_created, 
                                             #which contains the names of any new files
for my $path (@new_file_paths) {
    my ($base, $fname, $ext) = fileparse($path, '.log'); # $ext is "" if the '.log' extension is
                                                         # not found, otherwise it's '.log'.
    if ($ext eq '.log') {
        print "$path was created\n";
        if(-z $path){
        # i need to wait until something is written to log
        }else{
        my @arrr = `head -30 $path`;
        foreach(@arr){
         if(/Tool1/){
           system("/usr/bin/perl $script1 $path \&");
        }elsif(/Tool1/){
        system("/usr/bin/perl $script2 $path \&");
        }
    }
}
}
my $monitor = File::Monitor->new();
$monitor->watch( {
name        => $dir,
recurse     => 1,
callback    => {files_created => \&textfile_notifier},  #event => handler
} );
$monitor->scan;

while(1){
    $monitor->scan;
}

基本上我是从日志中获取一些重要信息。

您正在监视日志文件的创建。也许你可以在回调 sub 中使用睡眠函数来等待日志文件被写入。您也可以监视文件更改,因为可以扩展某些日志文件。

对于您问题的这种表述,类似的内容可能会对您有所帮助:

use File::Tail;
# for log file $logname
my @logdata;
my $file = File::Tail->new(name => $logname, maxinterval => 1);
while (defined(my $newline = $file->read)) {
    push @logdata, $newline;
    # the decision to launch the script according to data in @logdata
}

阅读更多here