What exactly does Perl's "bless" do?

user47145 picture user47145 · Dec 24, 2008 · Viewed 102.2k times · Source

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 ?

Answer

Gordon Wilson picture Gordon Wilson · Dec 24, 2008

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.