为什么Perl 5的函数原型很糟糕? [英] Why are Perl 5's function prototypes bad?

查看:154
本文介绍了为什么Perl 5的函数原型很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个Stack 溢出问题 Leon Timmermans 断言:


我建议你不要使用原型。他们有他们的用途,但不是在大多数情况下,绝对不在这一个。


为什么这可能是真的(或以其他方式)?我几乎总是为我的Perl函数提供原型,而且我以前从未见过其他人说过使用它们的任何错误。 解决方案

如果使用正确,原型也不错。困难在于Perl的原型不能像人们期望的那样工作。具有其他编程语言背景的人倾向于期望原型提供用于检查函数调用是否正确的机制:也就是说,他们拥有正确的数量和类型的参数。 Perl的原型并不适合这项任务。这是错误的 。 Perl的原型有一个奇异的目的:
$ b

原型允许你定义类似内置函数的函数。




  • 圆括号是可选的。

  • 上下文强加于参数。

  • <例如,你可以定义一个这样的函数:

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

    并称之为

      mypush @array,1,2,3; 

    无需将 \ 写入请引用数组。

    简而言之,原型可以让您创建自己的语法糖。例如,Moose框架使用它们来模拟更典型的面向对象语法。



    这非常有用,但原型非常有限:


    • 它们必须在编译时可见。

    • 它们可以绕过。

    • 传播上下文到参数可能会导致意外的行为。

    • 它们可以很难使用除
      严格规定的表单之外的任何其他函数调用函数。 ul>

      请参阅perlsub中的原型血淋淋的细节。


      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.

      解决方案

      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.

      这篇关于为什么Perl 5的函数原型很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆