Blessed References
Learn how to associate the name of the class with a reference.
Perl object system
Perl’s core object system is deliberately minimal. It has only three rules:
A class is a package.
A method is a function.
A (blessed) reference is an object.
We can build anything else out of these three rules. This minimalism can be impractical for larger projects, in particular, the possibilities for greater abstraction through
The bless
built-in
We’ve seen the first two rules already. The bless
built-in associates the name of a class with a reference. That reference is now a valid invocant. Perl will perform method dispatch on it. A constructor is a method that creates and blesses a reference. By convention, they are named new()
. Constructors are also almost always class methods.
bless
takes two operands, a reference and a class name, and evaluates to the reference. The reference may be any valid reference, empty or not. The class doesn't have to exist yet. We may even use bless
outside a constructor or a class, but we’d be violating encapsulation to expose the details of object construction outside a constructor. A constructor can be as simple as this:
Get hands-on with 1400+ tech skills courses.