【问题标题】:In Perl, how can I watch a directory for changes?在 Perl 中,如何查看目录的更改?
【发布时间】:2012-06-28 19:36:27
【问题描述】:
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.

您能告诉我为什么缺少统计信息以及如何解决吗?

【问题讨论】:

  • 我不相信那是你实际运行的代码。 $data_file 将包含文件的名称,后跟换行符,因此 open 将失败,因此它会死。 chomp 可以解决这个问题。还有许多其他问题,但是评论不是你的代码的东西有什么意义呢?我强烈建议您首先添加 use strict; use warnings; 并修复这些错误。
  • 它有文件,如您所见,它在第一行打印为“archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1500.dat”
  • 不,它有"archive/oswiostat/oracleapps.localdomain_iostat_12.06.28.1500.dat\n"
  • @ikegami,这是实际代码。在我的Linux系统上,根据strace,open(F, "newline\n")调用open("newline" *[sic]*, ...),但stat "newline\n"调用stat("newline\n" *[sic]*, ...)。你是对的,这是换行的麻烦。三参数 open 似乎保留了换行符 FWIW。
  • 那么解决方法是什么?

标签: perl filesystems change-notification


【解决方案1】:

真正的解决方法是 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 的两个参数形式,因为两个参数 open 模仿 shell 行为。但是,您对stat() 的调用不会忽略文件名中的换行符,因此stat() 是一个不存在的文件,因此$stats1undef

【讨论】:

  • @picrow 感谢帮助。很长一段时间后我正在接触perl,感谢您的快速帮助。我需要更正 if 循环中的 $stats2 。这个变量应该是全局的,我应该如何纠正这个。截至目前 stats2 显示为空。
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 2019-06-23
  • 2013-10-18
  • 2021-03-17
相关资源
最近更新 更多