Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `bless` do inside a brace construct?

Tags:

perl

my $self; { my %hash; $self = bless(\%hash, $pkg); }

It's quoted from HTML/Template.pm,why not simply bless $self,$pkg?

like image 704
Learning Avatar asked Jul 12 '11 06:07

Learning


2 Answers

I think the intention was to limit the scope of %hash to the enclosing block. This can be rewritten as:

my $self = bless {}, $pkg;
like image 124
Eugene Yarmash Avatar answered Oct 30 '22 00:10

Eugene Yarmash


 $hash  =   {};
 ^^^^^      ^^
referrer referent

In the following statement:

$self = bless( $hash, $pkg );

bless marks the referent (the anonymous hash) to which $hash refers, as being an object of $pkg (the HTML::Template class). It does not alter the $hash variable.

The bless function returns a reference to the blessed anonymous hash. $self therefore becomes a reference to the blessed anonymous hash (the referent).

It is important to remember that if the the first argument to the bless function is a reference, it is the thing to which it refers that is blessed, not the variable itself:

$self = bless( $self, $pkg );

$self doesn't refer to anything - it is undef. There is no referent to bless. It is equivalent to attempting this:

$self = bless( undef, $pkg );

Bless My Referents provides a great introduction to the subject.

like image 38
Mike Avatar answered Oct 30 '22 00:10

Mike