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.
精彩评论