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 ?
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 ?
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.)
Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).
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;
}
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.