Classes and bless
A class is just a package, and bless turns an ordinary reference into an object of that class.
In this page:
Classes and bless
bless takes a reference and a class name and marks the reference as belonging to that package. By convention a subroutine named new is the constructor: it creates a hash reference holding the object's data, blesses it and returns it. Calling Class->new(...) passes the class name as the first argument.
Note:
Pass the class name you received to bless, as in bless($self, $class), instead of hard-coding it, so subclasses work.
Example: Classes and bless
use strict;
use warnings;
package Dog;
sub new {
my ($class, %args) = @_;
my $self = {
name => $args{name} || "Unnamed",
sound => $args{sound} || "Woof",
};
return bless $self, $class;
}
package main;
my $dog = Dog->new(name => "Rex");
print "object class: ", ref($dog), "\n";
print "name stored: $dog->{name}\n";
print "sound stored: $dog->{sound}\n";
my $stray = Dog->new;
print "default name: $stray->{name}\n";
# Output:
# object class: Dog
# name stored: Rex
# sound stored: Woof
# default name: Unnamed
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to return the blessed reference from new
- Hard-coding the class name in bless
- Blessing a copy of the data instead of the reference you return
Chapter Summary
- A class is a package
- bless ties a reference to a package
- new is the conventional constructor
- Objects are usually blessed hash references
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: