ennuikiller
ennuikiller

Reputation: 46965

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

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 }

Upvotes: 4

Views: 230

Answers (3)

hobbs
hobbs

Reputation: 239841

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.

Upvotes: 12

FMc
FMc

Reputation: 42411

From perlsub on the topic of constant functions:

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

Upvotes: 11

Eugene Yarmash
Eugene Yarmash

Reputation: 149756

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

See Constant Functions in perlsub.

Upvotes: 7

Related Questions