Why are Perl 5's function prototypes bad?

后端 未结 4 1313
一个人的身影
一个人的身影 2020-11-22 03:56

In another Stack Overflow question Leon Timmermans asserted:

I would advice you not to use prototypes. They have their uses, but not for most cas

4条回答
  •  粉色の甜心
    2020-11-22 04:46

    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.

提交回复
热议问题