tags:

views:

5495

answers:

4

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 ?

+4  A: 

See "Bless My Referents" back from 1999. Looks pretty detailed. (The Perl manual entry doesn't have a great deal to say on it, unfortunately.)

Jon Skeet
+3  A: 

Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).

chaos
+11  A: 

In general, bless associates an object with a class.

package MyClass;
my $object = { };
bless $object, "MyClass";

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

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

Gordon Wilson
+17  A: 

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

kixx
Your initial statement is incorrect. Yes, bless takes a reference as its first argument, but it is the referent variable that is blessed, not the reference itself. $ perl -le 'sub Somepackage::foo {42}; %h=(); $h=\%h; bless $h, "Somepackage"; $j = \%h; print $j->UNIVERSAL::can("foo")->()'42
converter42
Kixx's explanation is comprehensive. We should not bother with converter's picking on theoretical minutiae.
Blessed Geek