使用File :: ChangeNotify模块监视文件夹时,如何获取已修改的文件

时间:2015-12-03 13:26:24

标签: perl file monitor

#!/opt/perl_5.18.2/linux50/bin/perl

use strict;
#use warnings;

use File::ChangeNotify;

$| = 1;

my $watcher = File::ChangeNotify->instantiate_watcher(
    directories => [ '/var/icc_shantesh/logs' ],
    filter      => qr/\.log/,
);

while ( my @events = $watcher->wait_for_events ) {
    print "loop got executed\n";
    print "File name: $_\n";
}

我在R& D环境中的上述代码中使用了File::ChangeNotify。该脚本监视文件夹,并在发生更改时通知。我想知道已更改的文件的名称及其更新的内容

1 个答案:

答案 0 :(得分:4)

@events数组包含您想要的信息:

 while (my @events = $watcher->wait_for_events){
    print "loop got executed\n";
    foreach my $event (@events) {
        print "File name: " . $event->path . "\n";
    }
 }

该数组包含File::ChangeNotify::Event个对象,它们具有path文件名访问器,type表示已进行了哪些更改。

您可以查看手册页上的示例,并将代码重写为:

 for my $event ( $watcher->new_events() ) {
     print "File name: ", $event->path(), ' - ', $event->type(), "\n";
 }

$_是perl的默认变量,但是当您在循环中显式设置变量时(my @events = ...$_未被使用。