Perl 的“祝福"究竟是什么?做? [英] What exactly does Perl's "bless" do?
本文介绍了Perl 的“祝福"究竟是什么?做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道有人在类的new"方法中使用 Perl 中的bless"关键字:
I understand one uses the "bless" keyword in Perl inside a class's "new" method:
sub new {
my $self = bless { };
return $self;
}
但是bless"到底对那个哈希引用做了什么?
But what exactly is "bless" doing to that hash reference ?
推荐答案
一般来说,bless
将一个对象与一个类相关联.
In general, bless
associates an object with a class.
package MyClass;
my $object = { };
bless $object, "MyClass";
现在,当您在 $object
上调用方法时,Perl 知道要搜索该方法的包.
Now when you invoke a method on $object
, Perl know which package to search for the method.
如果省略第二个参数,如在您的示例中,则使用当前包/类.
If the second argument is omitted, as in your example, the current package/class is used.
为了清楚起见,您的示例可能会写成如下:
For the sake of clarity, your example might be written as follows:
sub new {
my $class = shift;
my $self = { };
bless $self, $class;
}
See kixx's good answer for a little more detail.
这篇关于Perl 的“祝福"究竟是什么?做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文