Perl does not have type signatures or formal parameters, unlike other languages like C:
// C code
int add(int, int);
int sum = add(1, 2);
int add(int x, int y) {
return x + y;
}
Traditional Perl approach
Instead, the arguments are just passed as a flat list. Any type validation happens inside your code; you'll have to write this manually (but see below). You have to unpack the arglist into named variables yourself. And you don't usually predeclare your subroutines:
my $sum = add(1, 2);
sub add {
my ($x, $y) = @_; # Unpack arguments
return $x + $y;
}
If you predeclare your subs, you get the following:
- You can call the subs without parens
- You can change the way arguments are parsed with “prototypes”
Subroutine prototypes
A prototype can say
- evaluate this argument in scalar context:
sub foo($)
, or
- this argument must be a hash variable, please pass it as a reference:
sub foo(\%)
, or
- this sub takes no arguments:
sub foo()
, etc.
Don't use these to validate the number of arguments. Actually, don't use them at all; they cause action at a distance. They aren't useful for type validation either.
Your error stems from the fact that you declared your sub as nullary, this caused a parse error.
Signatures
If you want the ability to declare your subroutines with named parameters, you can use a module that implements these.
From Perl 5.20 onwards, you can use feature 'signatures'
. It is still marked as experimental, but the basic syntax is unlikely to change.
use feature 'signatures';
no warnings 'experimental::signatures'
sub add($x, $y) { ... }
There are various CPAN modules like Method::Signatures
. They might have benefits like integrated type checks, but can also be more buggy than solutions implemented in Core Perl.
use Method::Signatures;
func add(Int $x, Int $y) { ... }
However, these “signatures” have nothing to do with the prototypes of plain subs.