Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }
like image 254
ennuikiller Avatar asked Nov 28 '22 10:11

ennuikiller


1 Answers

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.

like image 191
hobbs Avatar answered Dec 05 '22 05:12

hobbs