Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I need to set up something where I am notified when a Directory gets a new file. I can handle puttin the email part in but how would I set up something to check when a new file is added to an NT directory?

Should I do a count on files and then find out if count has change? Please advise as I dont know how I can do a count and then check if a new file was added? Or any other way to do this?? Here is my start on trying this:
use strict; $newfile = "./"; my $ct=0; opendir(DIR,$newfile) || die "Can not open directory: $!"; my @files = readdir(DIR); foreach(@files){ $ct++; } close(DIR);

Replies are listed 'Best First'.
Re: Adding file to directory notification
by John M. Dlugosz (Monsignor) on Nov 12, 2002 at 20:13 UTC
    Win32 has native abilities to do this.

    On all Win32 OS's, you can use FindFirstChangeNotification et.al. You can access Windows API functions with Win32::API, or many are already wrapped in nice Perl modules. I used this once from Perl just in playing around, so I know it can be done.

    On NT/2000/XP, you can use ReadDirectoryChangesW which gives more detailed info than "something changed!". On 2000/XP (I think it started in win2k) there is a similar feature that's sticky, and can report changes that occured even when you were not running and activly watching for them.

    —John

Re: Adding file to directory notification
by robartes (Priest) on Nov 12, 2002 at 20:13 UTC
    One simple way is to keep a hash with the previous filelist in it. Something like:
    use strict; opendir(DIR,$newfile) or die "Blerch: $!\n"; my %files=map {$_,1} readdir(DIR); #assume %oldfiles was set before in a similar way foreach my $file (keys %newfiles) { unless (exists $oldfiles{$file}) do_we_have_a_new_file(); #Cheers an +d happiness!! }
    You use a hash instead of an array because you're searching for stuff (in this case filenames), which is faster and easier using hashes.

    Beware that this code is untested and might do unpredictable things, including actually working.

    CU
    Robartes-

    Update: Corrected some silly syntax mistakes.