我想知道是否有办法等待文件更新,然后一旦更新就读取它.所以,如果我有file.txt,我想等到新的东西写入它,然后读它/处理它/等.目前我正在使用轮询Time::HiRes::sleep(.01),但我想知道是否有更好的方法.谢谢.
是的,有更好的方法.在Windows上,您可以使用FileSystemWatcher接口,在Linux上使用inotify.
视窗
use Win32::FileSystem::Watcher;
my $watcher = Win32::FileSystem::Watcher->new( "c:\\" );
# or
my $watcher = Win32::FileSystem::Watcher->new(
"c:\\",
notify_filter => FILE_NOTIFY_ALL,
watch_sub_tree => 1,
);
$watcher->start();
print "Monitoring started.";
sleep(5);
# Get a list of changes since start().
my @entries = $watcher->get_results();
# Get a list of changes since the last get_results()
@entries = $watcher->get_results();
# ... repeat as needed ...
$watcher->stop(); # or undef $watcher
foreach my $entry (@entries) {
print $entry->action_name . " " . $entry->file_name . "\n";
}
# Restart monitoring
# $watcher->start();
# ...
# $watcher->stop();
Run Code Online (Sandbox Code Playgroud)
LINUX
use Linux::Inotify2;
my $inotify = new Linux::Inotify2();
foreach (@ARGV)
{
$inotify->watch($_, IN_ALL_EVENTS);
}
while (1)
{
# By default this will block until something is read
my @events = $inotify->read();
if (scalar(@events)==0)
{
print "read error: $!";
last;
}
foreach (@events)
{
printf "File: %s; Mask: %d\n", $_->fullname, $_->mask;
}
}
Run Code Online (Sandbox Code Playgroud)