Windows - 使用perl监视目录以进行新文件删除/创建

时间:2014-05-19 06:47:47

标签: windows perl

寻找监视目录以创建新文件或删除文件的方法。

所以,如果我有一个文件夹c:\ temp,并且如果在此复制/创建了一个abc.txt,我想要一个事件或其他东西,以便我可以拿起该文件然后处理它。

另外,我想要连续监控这个文件夹。我怎样才能做到这一点。我正在写一个完成所有这些工作的服务。我想在一个脚本中加入监控和处理。

提前致谢。

1 个答案:

答案 0 :(得分:3)

答案在这里:In Perl, how can I watch a directory for changes?

对于Linux:

use File::ChangeNotify;

my $watcher = File::ChangeNotify->instantiate_watcher(
    directories => [ 'archive/oswiostat' ],
    filter => qr/\Aoracleapps[.].*dat\z/,
);

while (my @events = $watcher->wait_for_events) {
    # ...
}

我认为您使用的是Windows,因此您必须使用Win32 :: ChangeNotify

示例来自:http://www.perlmonks.org/?node_id=306175

use strict;
use Win32::ChangeNotify;

our $PATH ||= '.';
our $S = defined $S ? 1 : 0;

my $notify = Win32::ChangeNotify->new( $PATH, $S, 'FILE_NAME' );

my %last; @last{ glob $PATH . '/*' } = ();

while( 1 ) {
    print('Nothing changed'), next
        unless $notify->wait( 10_000 ); # Check every 10 seconds
    $notify->reset;
    print 'Something changed';
    my @files = glob $PATH . '/*';
    if( @files < scalar keys %last ) {
        delete @last{ @files };
        print 'These files where deleted: ';
        print for keys %last;
    }
    elsif( @files > scalar keys %last ) {
        my %temp;
        @temp{ @files } = ();
        delete @temp{ keys %last };
        print 'These files where created: ';
        print for keys %temp;
    }
    else {
        print "A non-deletion or creation change occured";
    }
    undef %last;
    @last{ @files } = ();
}