开发者

What does () accomplish in a subroutine definition in Perl?

开发者 https://www.devze.com 2023-01-21 05:49 出处:网络
The following code is lifted directly from the source of the Tie::File module.What do the empty parentheses accomplish in the definiti开发者_JAVA技巧on of O_ACCMODE in this context?I know what subrout

The following code is lifted directly from the source of the Tie::File module. What do the empty parentheses accomplish in the definiti开发者_JAVA技巧on 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 }


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:

sub FOO { 1 }
sub BAR { 2 }

print FOO + BAR;

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:

sub FOO () { 1 }
sub BAR () { 2 }

print FOO + BAR;

The final line parses as print FOO() + BAR() and the value printed is 3, because the () prototype tells the parser that no arguments to FOO are expected or valid.


From perlsub on the topic of constant functions:

Functions with a prototype of () are potential candidates for inlining


The prototype of () makes the subroutine eligible for inlining. This is used by the constant pragma, for example.

See Constant Functions in perlsub.

0

精彩评论

暂无评论...
验证码 换一张
取 消