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

查看:33
本文介绍了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}

这可能不是您想要的.

另一个问题是,如果您的包中恰好有​​一个与您尝试调用的方法同名的函数.例如,如果您使用的某个模块导出了一个名为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天全站免登陆