Perl’s Object System
Perl doesn’t provide any special syntax for defining objects, classes, or methods. Instead, it reuses existing constructs to implement these three concepts.[142] Here are some simple definitions that you may find reassuring:
- An object is simply a reference…er, a referent.
Since references let individual scalars represent larger collections of data, it shouldn’t be a surprise that references are used for all objects. Technically, an object isn’t the reference proper—it’s really the referent that the reference points at. This distinction is frequently blurred by Perl programmers, however, and since we feel it’s a lovely metonymy, we will perpetuate the usage here when it suits us.[143]
- A class is simply a package.
A package serves as a class by using the package’s subroutines to execute the class’s methods, and by using the package’s variables to hold the class’s global data. Often, a module is used to hold one or more classes.
- A method is simply a subroutine.
You just declare subroutines in the package you’re using as the class; these will then be used as the class’s methods. Method invocation, a new way to call subroutines, passes an extra argument: the object or package used for invoking the method.
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