() 在 Perl 中的子例程定义中完成什么作用?
以下代码直接从 Tie::File 模块的源代码中提取。在这种情况下,O_ACCMODE 定义中的空括号有何作用?我知道子例程原型的用途是什么,但这种用法似乎与此无关。
use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'LOCK_SH', 'O_WRONLY', 'O_RDONLY';
sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }
The following code is lifted directly from the source of the Tie::File module. What do the empty parentheses accomplish in the definition of O_ACCMODE in this context? I know what subroutine prototypes are used for, but this usage doesn't seem to relate to that.
use Fcntl 'O_CREAT', 'O_RDWR', 'LOCK_EX', 'LOCK_SH', 'O_WRONLY', 'O_RDONLY';
sub O_ACCMODE () { O_RDONLY | O_RDWR | O_WRONLY }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
()
的原型使子例程符合内联条件。例如,constant
pragma 使用它。请参阅 perlsub 中的常量函数。
The prototype of
()
makes the subroutine eligible for inlining. This is used by theconstant
pragma, for example.See Constant Functions in perlsub.
它还告诉解析器
O_ACCMODE
在任何情况下都不接受参数(&O_ACCMODE()
除外,您可能永远不必考虑它)。这使得它的行为就像大多数人期望的那样。举个简单的例子,在:
最后一行解析为
print FOO(+BAR())
并且打印的值为 1,因为当在没有括号的情况下调用无原型 sub 时,它会尝试像 listop 一样运行并尽可能正确地消化术语。In:
最后一行解析为
print FOO() + BAR()
并且打印的值为 3,因为()
原型告诉解析器没有参数FOO
是预期的或有效的。It also tells the parser that
O_ACCMODE
doesn't take an argument under any condition (except&O_ACCMODE()
which you will likely never have to think about). This makes it behave like most people expect a constant to.As a quick example, in:
the final line parses as
print FOO(+BAR())
and the value printed is 1, because when a prototypeless sub is called without parens it tries to act like a listop and slurp terms as far right as it can.In:
The final line parses as
print FOO() + BAR()
and the value printed is 3, because the()
prototype tells the parser that no arguments toFOO
are expected or valid.来自 perlsub 关于常量函数的主题:
From perlsub on the topic of constant functions: