gpt4 book ai didi

perl - 等待文件更新然后在 Perl 中读取文件的好方法是什么?

转载 作者:行者123 更新时间:2023-12-02 08:35:01 25 4
gpt4 key购买 nike

我想知道是否有一种方法可以等待文件更新,然后在更新后从中读取。因此,如果我有 file.txt,我想等到有新内容写入其中,然后读取它/处理它/等等。目前我正在使用 Time::HiRes::sleep(.01) 进行轮询,但我想知道是否有更好的方法。谢谢。

最佳答案

是的,有更好的方法。在 Windows 上,您可以使用 FileSystemWatcher接口(interface),在 Linux 上,使用 inotify

Windows

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();

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;
}
}

关于perl - 等待文件更新然后在 Perl 中读取文件的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2367413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com