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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…