In Perl, how can I watch a directory for changes?

后端 未结 2 715
清酒与你
清酒与你 2021-01-15 20:49
use Text::Diff;
for($count = 0; $count <= 1000; $count++){
   my $data_dir=\"archive/oswiostat/oracleapps.*dat\";
   my $data_file= `ls -t $data_dir | head -1`;
          


        
相关标签:
2条回答
  • 2021-01-15 21:29

    Note that I'm answering your original question, why the stat() seemed to fail, rather than the newly edited question title, which asks something different.

    This is the fix:

    my $data_file= `ls -t $data_dir | head -1`;
    chomp($data_file);
    

    The reason this is the fix is a little murky. Without that chomp(), $data_file contains a trailing newline: "some_filename\n". The two argument form of open() ignores trailing newlines in filenames and I don't know why because two-arg open mimics shell behavior. Your call to stat(), however, does not ignore the newline in the filename, so it is stat()ing a non-existent file and thus $stats1 is undef.

    0 讨论(0)
  • 2021-01-15 21:43

    The real fix is File::ChangeNotify or File::Monitor or something similar (e.g., on Windows, Win32::ChangeNotify).

    use File::ChangeNotify;
    
    my $watcher = File::ChangeNotify->instantiate_watcher(
        directories => [ 'archive/oswiostat' ],
        filter => qr/\Aoracleapps[.].*dat\z/,
    );
    
    while (my @events = $watcher->wait_for_events) {
        # ...
    }
    
    0 讨论(0)
提交回复
热议问题