1

i need to watch files that fall under a directory.I have coded the below script in perl . but it is not doing what i want .

  1. whenever a file or files arrives , it has to do a movement .
  2. And then it has to keep watching files again.
  3. the script should be running in background.

    #!/usr/bin/perl
    use warnings;
    use File::Copy qw(move);
    $src_dir = '/root/prasanna/dir';
    $tgt_dir = '/root/prasanna/dir/dir1';
    while (true) {
        opendir( DIR, "/root/prasanna/dir" )
            or die "Cannot open  /root/prasanna/dir: $!\n";
        my @Dircontent = readdir DIR;
        close DIR;
        my $items = @Dircontent;
        if ( $items > 2 ) {
            print "files available";
            while ($items) {
                print $items;
                move $src_dir. '/' . $items, $tgt_dir . '/' . $items;
                unlink $items;
            }
        }
        else { sleep 50; }
    }
    

The problem with the above code is 1. the if statement keeps on printing the 'files available' . goes on infinite loop , it doesnt watch for files again .even if i do operations on file, i dont knw how to make it look for files again. 2. the script doesnt run in background .

any help is highly appreciated . thanks beforehand.!

Sobrique
  • 52,974
  • 7
  • 60
  • 101
prasannads
  • 609
  • 2
  • 14
  • 28
  • Please format the code to improve readability. – Joeblade Jan 19 '15 at 09:48
  • I've just tried to reformat/fix your code - what you've pasted there. It's a) incompleted, and b) issue warnings. Fix warnings, turn on `use strict` and format your code and you'll get much better answers. – Sobrique Jan 19 '15 at 09:59
  • @joeblade im not able to edit in a way to put the code in separate lines. it shows error then. – prasannads Jan 19 '15 at 09:59
  • 1
    I've applied an edit to fix formatting. I've had to add a trailing bracket, because one was missing. Please can you check that code as edited is what you've got? – Sobrique Jan 19 '15 at 10:01
  • looking much better :) thanks @Sobrique – Joeblade Jan 19 '15 at 10:04

1 Answers1

0

presuming you are running under Linux, use Linux::Inotify2...

use Linux::Inotify2;

# create an Inotify object
my $Inotify = Linux::Inotify2->new() or die "Fail: $!";

# choose which operations for which you wish to be notified
my $watchme = IN_CLOSE_WRITE | IN_CREATE | IN_MOVED_TO; # defined and exported

$Inotify->watch('/root/prasanna/dir', $watchme, \&watcher) or die "Fail: $!";

while (1) {
    $Inotify->poll;
}

sub watcher
{
  # do something here
}

Note it can only monitor local filesystems (i.e. no NFS mounts)

davidc
  • 71
  • 2