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

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

问题描述

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

我建议你不要使用原型.它们有其用途,但不适用于大多数情况,绝对不是在这种情况下.

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

为什么这可能是真的(或不然)?我几乎总是为我的 Perl 函数提供原型,而且我以前从未见过其他人说使用它们不好.

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.

推荐答案

如果使用得当,原型也不错.困难在于 Perl 的原型并不像人们通常期望的那样工作.具有其他编程语言背景的人倾向于期望原型提供一种机制来检查函数调用是否正确:也就是说,它们具有正确的参数数量和类型.Perl 的原型并不适合这项任务.不好的是滥用.Perl 的原型有一个独特而非常不同的目的:

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:

原型允许您定义行为类似于内置函数的函数.

  • 括号是可选的.
  • 上下文强加于参数.

例如,您可以像这样定义一个函数:

For example, you could define a function like this:

sub mypush(@@) { ... }

并称之为

mypush @array, 1, 2, 3;

无需编写 来引用数组.

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

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

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:

  • 它们必须在编译时可见.
  • 它们可以被绕过.
  • 将上下文传播到参数可能会导致意外行为.
  • 它们会使使用除严格规定的表格.

请参阅 perlsub 中的 Prototypes 了解所有详细信息.

See Prototypes in perlsub for all the gory details.

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

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