在Perl中,如何查看目录以进行更改?

时间:2012-06-28 19:36:27

标签: perl filesystems change-notification

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`;
   while($data_file){
      print $data_file;
      open (DAT,$data_file) || die("Could not open file! $!");
      $stats1 = (stat $data_file)[9];
      print "Stats: \n";
      @raw_data=<DAT>;
      close(DAT);
      print "Stats1 is :$stats1\n";
      sleep(5);
      if($stats1 != $stats2){
         @diff = diff \@raw_data, $data_file, { STYLE => "Context" };
         $stats2 = $stats1;
      }
      print @diff || die ("Didn't see any updates $!");
   }
}

输出:

$ perl client_socket.pl
archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1500.dat
Stats:
Stats1 is :
Didn't see any updates  at client_socket.pl line 18.

你能告诉我为什么缺少统计数据以及如何解决这个问题吗?

2 个答案:

答案 0 :(得分:14)

真正的修复方法是File::ChangeNotifyFile::Monitor或类似内容(例如,在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) {
    # ...
}

答案 1 :(得分:2)

请注意,我正在回答您的原始问题,为什么stat()似乎失败了,而不是新编辑的问题标题,它会提出不同的问题。

这是修复:

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

原因这是修复有点模糊。如果没有chomp(),则$data_file包含一个尾随换行符:"some_filename\n"open() ignores trailing newlines in filenames and I don't know why的两个参数形式,因为两个arg打开模仿shell行为。但是,您对stat()的调用不会忽略文件名中的换行符,因此stat()存在一个不存在的文件,因此$stats1undef