Problems and Uses of Prototypes

Learn when to use prototypes and when not to use them.

The problem with prototypes

Prototypes change how Perl parses our code and how Perl coerces arguments passed to our functions. While these prototypes may superficially resemble function signatures in other languages, they’re very different. They don’t document the number or types of arguments functions expect, nor do they map arguments to named parameters.

Prototype coercions work in subtle ways, such as enforcing scalar context on incoming arguments:

Press + to interact
sub numeric_equality($$) {
my ($left, $right) = @_;
return $left == $right;
}
my @nums = 1 .. 10;
say "They're equal, whatever that means!" if numeric_equality @nums, 10;

But they work only on simple expressions:

Press + to interact
sub mypush(\@@);
# compilation error: prototype mismatch
# (expects array, gets scalar assignment)
mypush( my $elems = [], 1 .. 20 );
say "$elems";

To debug this, users of mypush must know both that a ...