本文介绍了Windows - 使用 perl 监视目录以删除/创建新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在寻找一种方法来监视目录是否有新文件创建或删除.

Looking for a way to monitor a directory for a new file creation or a drop.

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

so if I have a folder c:\temp and if an abc.txt is copied/created in this I want an event or something so that I can pick up that file and then process it.

另外,我想持续监控这个文件夹.我怎样才能做到这一点.我正在编写一个服务来完成所有这些.我想将监控和处理整合到一个脚本中.

Also, I want continuous monitoring of this folder. How can I do that. I am writing a service which does all this. I want to incorporate monitoring and processing in one script.

提前致谢.

推荐答案

答案在这里:在 Perl 中,如何查看目录的更改?

对于 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

I think you are using Windows so you have to use 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 } = ();
}

这篇关于Windows - 使用 perl 监视目录以删除/创建新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:25