2

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

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.

Thanks in advance.

Avenger789
  • 402
  • 4
  • 14

1 Answers1

2

The answer is here: In Perl, how can I watch a directory for changes?

For 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) {
    # ...
}

I think you are using Windows so you have to use Win32::ChangeNotify

example from: 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 } = ();
}
Community
  • 1
  • 1
user1126070
  • 5,059
  • 1
  • 16
  • 15
  • This somehow doesn't work. I had tried it yesterday. – Avenger789 May 20 '14 at 02:16
  • It just never gave me any output even if I changed anything in that folder. Never mind. I decided against using the continuous monitoring of the folder and will poll the folder at appropriate duration. Thanks for your efforts. – Avenger789 May 22 '14 at 06:10
  • I don['t quite understand the comma in `print('Nothing changed'), next ..`. If I replace it with a semicolon the script seems to work fine. – perlyking Jun 03 '15 at 13:38
  • Also doesn't work for me. No output, no errors, nothing. I create a file in the same folder as the perl script and everything stays silent :( – Pedro Araujo Jorge Nov 09 '20 at 11:02