25.11. Objects
Perl has robust support for object data types. Although a full description of object-oriented programming is beyond the scope of this book, the following sections provide a primer on Perl's handling of objects.
25.11.1. Perl's Object Nomenclature
As with all things Perl, there are several ways (and related syntax) to achieve a desired goal. In this case, there are several ways to work with objects. We will stick with the standard -> separator syntax familiar to most object-oriented programmers.
This syntax uses -> to separate objects and methods. For example, when creating a new object of class dog, you use the new() method similarly to the following:
doberman = dog_object->new();
Object properties are assigned using the associative assignment operator, =>. This creates the properties as hashes (associative arrays) and has the benefit of providing a ready-made method for accessing property values using simple statements such as the following:
print %{doberman}->{'color'};
25.11.2. Perl Constructors
One easy way to create constructors is to use a separate namespace in Perl to create a new() function and associated initialization routines. For example, to create a constructor for the dog class, you could use code similar to the following:
package dog_object; sub new { my $class = shift; my %params = @_; bless { "color" => $params{"color"}, "size" => $params{"size"} }, $class; }
This code defines a new namespace (dog_object) where the new() function can be initialized ...
Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.