my $self; { my %hash; $self = bless(\%hash, $pkg); }
Run Code Online (Sandbox Code Playgroud)
它引用了HTML/Template.pm
,为什么不简单bless $self,$pkg
?
因为$self
是undef
- 几乎等同于:
my $self ={}; { $self = bless($self, $pkg); }
Run Code Online (Sandbox Code Playgroud)
或者 :
$self = bless( {}, $pkg);
Run Code Online (Sandbox Code Playgroud)
编辑回答评论:
你不能祝福 undef,因为你会得到 error Can't bless non-reference value at ...
。这是因为只有硬引用可能会受到祝福。这就是 Perl强制对象封装的方式。请参阅perlobj 联机帮助页。