Perl的“祝福"到底是什么?做? [英] What exactly does Perl's "bless" do?

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

但是祝福"到底是对那个哈希引用做什么呢?

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; 
} 

请参见 kixx 的好

See kixx's good answer for a little more detail.

这篇关于Perl的“祝福"到底是什么?做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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