What is the difference between a Perl signature with and without parentheses?

What exactly is the difference (if any) between:

sub foobar() { # doing some stuff } 

and

 sub foobar { # doing some stuff } 

I see some of them, and the first syntax sometimes fails to compile.

+6
source share
1 answer

By placing () at the end of the subroutine name, you give it a prototype. The prototype gives Perl hints about the number and type of arguments you pass to the routine. See this section in perlsub for details .

In particular, () is an empty prototype that tells Perl that this routine does not accept any arguments, and Perl will throw a compilation error if you call this routine with arguments. Here is an example:

 #!/usr/bin/perl use strict; use warnings; use 5.010; sub foo { say 'In foo'; } sub bar() { say 'In bar'; } foo(); bar(); foo(1); bar(1); 

The way out of this:

 Too many arguments for main::bar at ./foobar line 18, near "1)" Execution of ./foobar aborted due to compilation errors. 

This is the last call to bar() (the one with argument 1) that causes this error.

It is worth noting that implementing Perl prototypes is usually not as useful as people often think they are, and that outside of a few specialized cases, most Perl experts shy away from them. I recommend that you do the same. Starting with Perl v5.22, the experimental “signatures” feature is in testing, which we hope will perform many of the tasks that programmers from other languages ​​expected from prototypes.

+9
source

All Articles