Why are Perl 5's function prototypes bad?

Alnitak picture Alnitak · Nov 17, 2008 · Viewed 19k times · Source

In another Stack Overflow question Leon Timmermans asserted:

I would advice you not to use prototypes. They have their uses, but not for most cases and definitely not in this one.

Why might this be true (or otherwise)? I almost always supply prototypes for my Perl functions, and I've never before seen anyone else say anything bad about using them.

Answer

Michael Carman picture Michael Carman · Nov 17, 2008

Prototypes aren't bad if used correctly. The difficulty is that Perl's prototypes don't work the way people often expect them to. People with a background in other programming languages tend to expect prototypes to provide a mechanism for checking that function calls are correct: that is, that they have the right number and type of arguments. Perl's prototypes are not well-suited for this task. It's the misuse that's bad. Perl's prototypes have a singular and very different purpose:

Prototypes allow you to define functions that behave like built-in functions.

  • Parentheses are optional.
  • Context is imposed on the arguments.

For example, you could define a function like this:

sub mypush(\@@) { ... }

and call it as

mypush @array, 1, 2, 3;

without needing to write the \ to take a reference to the array.

In a nutshell, prototypes let you create your own syntactic sugar. For example the Moose framework uses them to emulate a more typical OO syntax.

This is very useful but prototypes are very limited:

  • They have to be visible at compile-time.
  • They can be bypassed.
  • Propagating context to arguments can cause unexpected behavior.
  • They can make it difficult to call functions using anything other than the strictly prescribed form.

See Prototypes in perlsub for all the gory details.