Initializers
Most objects maintain internal information that is indirectly manipulated by the object’s methods. All our constructors so far have created empty hashes, but there’s no reason to leave them empty. For instance, we could have the constructor accept extra arguments to store into the hash as key/value pairs. The OO literature often refers to such data as properties, attributes, accessors, accessor method, member data, instance data, or instance variables. The section “Instance Variables”, later in this chapter, discusses attributes in more detail.
Imagine a Horse class with
instance attributes like “name” and “color”:
$steed = Horse–>new(name => "Shadowfax", color => "white");
If the object is implemented as a hash reference, the key/value pairs can be interpolated directly into the hash once the invocant is removed from the argument list:
sub new {
my $invocant = shift;
my $class = ref($invocant) || $invocant;
my $self = { @_ }; # Remaining args become attributes
bless($self, $class); # Bestow objecthood
return $self;
}This time we used a method named new for the class’s constructor, which just
might lull C++ programmers into thinking they know what’s going on. But
Perl doesn’t consider “new” to be anything special; you may name your constructors whatever you like. Any method that happens to create and return an object is a de facto constructor. In general, we recommend that you name your constructors whatever makes sense in the context of the problem you’re solving. For ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access