在一段时间内有条件地测试文件存在是否存在任何陷阱?
我最近遇到了一行有趣的代码,它会等待特定的文件启动:
sleep 1 until -e $file;
虽然从表面上看,该行代码执行了人们期望的操作,但我不禁感到这里有些不对劲;编写以下内容似乎更自然:
while (1) {
sleep 1;
last if -e $file;
}
文件测试运算符是否仅用于 if
和 unless
?在 while 条件语句中部署此类运算符是否会带来性能损失?
I recently came across an interesting line of code that waits until a particular file springs to life:
sleep 1 until -e $file;
While at face value the line does what one expects it to, I can't but help feel that something is not right here; it just seems more natural to write the following:
while (1) {
sleep 1;
last if -e $file;
}
Are the file test operators intended for use only with if
and unless
? And are there any performance penalties in deploying such operators within while
conditionals?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 while-true (
while
) 和 while-false (until
) 循环中使用文件测试运算符,或者使用if
/unless
,与 Perl 中的其他内容也没有区别。while 循环唯一神奇的情况是
... while <$handle>;
或while (<$handle>) {...}
,它设置 < code>$_ 到定义时的下一行。使用带有裸句柄的 while-false (until
) 循环并没有真正的意义。a Until b
构造只是a while not b
。要将
sleep 1 Until -e $file;
转换为while
循环,您可以使用以下代码:然后可以将其扩展为块形式:
或者作为无限 < code>while 带有内部转义:
并且所有这些形式都是等效的。
回答您的问题的其余部分,大多数文件系统应该可以在检查之间休息 1 秒,但是如果进程不紧急等待文件,您可以通过多种方式选择更大的数字。此外,如果您使用的设备具有较慢的文件系统(存储在闪存中或通过较慢的网络),您可能也想尝试更大的值。
正如下面的 ysth 挑剔一样,一般来说,当语句形式是返回的构造的最后一个元素时,语句形式的返回与块形式不同:
do {...}
, <代码>sub {...},do FILE
,eval ...There is no difference between using a file test operator in a while-true (
while
) vs a while-false (until
) loop, or by separating out the test with anif
/unless
, nor is there a difference with anything else in Perl.The only magical case with the while loop is
... while <$handle>;
orwhile (<$handle>) {...}
which sets$_
to the next line while it is defined. And it doesn't really make sense to use the while-false (until
) loop with bare handles.The
a until b
construct is simplya while not b
.To convert
sleep 1 until -e $file;
into awhile
loop, you would use the following:This can then be expanded to the block form:
Or as an infinite
while
with internal escape:And all of these forms are equivalent.
Answering the rest of your question, most file systems should be fine with 1 second sleeps between checks, but you many way to pick a larger number if the process is not urgently waiting on the file. Also if you are on a device with a slow file system (stored in flash memory or via slow network) you might want to experiment with larger values as well.
And as
ysth
nitpicks below, in general, statement forms return differently than block forms when they are the last element of a construct that returns:do {...}
,sub {...}
,do FILE
, eval ...即使文件存在,您更自然的方式似乎也会在开始时睡眠。
对我来说似乎更好,这正是
sleep 1 Until -e $file;
的同义词,但在我看来更容易理解。Your more natural way seems to sleep at start even if the file exists.
seems better to me, which is exactly synonym of
sleep 1 until -e $file;
but more understandable in my opinion.