Perl中new Some :: Class和Some :: Class-> new()之间有什么区别? [英] What is the difference between new Some::Class and Some::Class->new() in Perl?

查看:133
本文介绍了Perl中new Some :: Class和Some :: Class-> new()之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多年前,我还记得有一位程序员在辅导这个问题:

Many years ago I remember a fellow programmer counselling this:

new Some::Class;    # bad! (but why?)

Some::Class->new(); # good!

现在,我不记得自己的原因了. :(即使构造函数实际上不存在于Some :: Class模块中,而是从某个地方的父级继承的,这两种形式也可以正常工作.

Sadly now I cannot remember the/his reason why. :( Both forms will work correctly even if the constructor does not actually exist in the Some::Class module but instead is inherited from a parent somewhere.

这两种形式都不与Some :: Class :: new()相同,后者不会将类的名称作为第一个参数传递给构造函数-因此,这种形式总是不正确的.

Neither of these forms are the same as Some::Class::new(), which will not pass the name of the class as the first parameter to the constructor -- so this form is always incorrect.

即使两种形式等效,我也会发现Some :: Class-> new()更加清晰,因为它遵循在模块上调用方法的标准约定,而在perl中则是"new"方法不是特别的-构造函数可以被命名为任何东西,而new()可以执行任何操作(尽管我们通常希望它是构造函数).

Even if the two forms are equivalent, I find Some::Class->new() to be much more clear, as it follows the standard convention for calling a method on a module, and in perl, the 'new' method is not special - a constructor could be called anything, and new() could do anything (although of course we generally expect it to be a constructor).

推荐答案

使用new Some::Class被称为间接"方法调用,这很糟糕,因为它在语法上引入了一些歧义.

Using new Some::Class is called "indirect" method invocation, and it's bad because it introduces some ambiguity into the syntax.

它可能失败的原因之一是,如果您有对象的数组或哈希.您可能会期望

One reason it can fail is if you have an array or hash of objects. You might expect

dosomethingwith $hashref->{obj}

等于

$hashref->{obj}->dosomethingwith();

但它实际上解析为:

$hashref->dosomethingwith->{obj}

可能不是您想要的.

另一个问题是,程序包中是否有一个函数与您要调用的方法同名.例如,如果您use的某个模块导出了一个名为dosomethingwith的函数,该怎么办?在这种情况下,dosomethingwith $object含糊不清,并可能导致令人困惑的错误.

Another problem is if there happens to be a function in your package with the same name as a method you're trying to call. For example, what if some module that you use'd exported a function called dosomethingwith? In that case, dosomethingwith $object is ambiguous, and can result in puzzling bugs.

使用->语法专门消除了这些问题,因为编译器始终清楚该方法以及您希望该方法执行的操作.

Using the -> syntax exclusively eliminates these problems, because the method and what you want the method to operate upon are always clear to the compiler.

这篇关于Perl中new Some :: Class和Some :: Class-> new()之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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