The &
sigil is not commonly used with function calls in modern Perl for two reasons. First, it is largely redundant since Perl will consider anything that looks like a function (followed by parens) a function. Secondly, there is a major difference between the way &function()
and &function
are executed, which may be confusing to less experienced Perl programmers. In the first case, the function is called with no arguments. In the second case, the function is called with the current @_
(and it can even make changes to the argument list which will be seen by later statements in that scope:
sub print_and_remove_first_arg {print 'first arg: ', shift, "\n"}
sub test {
&print_and_remove_first_arg;
print "remaining args: @_\n";
}
test 1, 2, 3;
prints
first arg: 1
remaining args: 2 3
So ultimately, using &
for every function call ends up hiding the few &function;
calls which can lead to hard to find bugs. In addition, using the &
sigil prevents the honoring of function prototypes, which can be useful in some cases (if you know what you are doing), but also may lead to hard to track down bugs. Ultimately, &
is a powerful modifier to function behavior, and should only be used when that behavior is desired.
Prototypes are similar, and their use should be limited in modern Perl. What must be stated explicitly is that prototypes in Perl are NOT function signatures. They are hints to the compiler that tell it to parse calls to those functions in a similar way as the built in functions. That is, each of the symbols in the prototype tells the compiler to impose that type of context on the argument. This functionality can be very helpful when defining functions that behave like map
or push
or keys
which all treat their first argument differently than a standard list operator would.
sub my_map (&@) {...} # first arg is either a block or explicit code reference
my @ret = my_map {some_function($_)} 1 .. 10;
The reason sub ($$) {...}
and similar uses of prototypes are discouraged is because 9 times out of 10 the author means "I want two args" and not "I want two args each with scalar context imposed on the call site". The former assertion is better written:
use Carp;
sub needs2 {
@_ == 2 or croak 'needs2 takes 2 arguments';
...
}
which would then allow the following calling style to work as expected:
my @array = (2, 4);
needs2 @array;
To sum up, both the &
sigil and function prototypes are useful and powerful tools, but they should only be used when that functionality is required. Their superfluous use (or misuse as argument validation) leads to unintended behavior and difficult to track down bugs.