Introduction to Object Oriented Perl
Peter Karman
What we'll cover
- Packages and classes
- References and objects
- Subroutines and methods
- Encapsulation, Inheritance and Polymorphism
Goal: feel comfortable reading object-oriented Perl code.
Idiom
Unlike most programming languages, Perl relies on idiom
and style and convention, rather than rigid syntax patterns, to enforce
its readability.
TIMTOWTDI (There Is More Than One Way To Do It)
However, there are usually only a couple of Best Ways to do it.
Rules
- Be polite.
- If it isn't documented, it doesn't exist.
Conventions
- Objects are blessed hash references. But don't peek.
- Private methods start with one or more underscore characters (_).
- Don't step in someone else's namespace.
Packages
A package is a namespace for subroutines
and variables. In Perl, a class and a package are the same thing.
All variables and subroutines belong to a package. The default
package name is main.
See code/class.pl
References
A reference is a scalar variable that refers to another
variable. A Perl reference is analogous to a C pointer.
my @array = (1, 2, 3);
my $array_ref = \@array;
push @$array_ref, 4;
print join(', ', @array); # 1, 2, 3, 4
See code/references.pl and code/complex-references.pl.
The Arrow Operator
The arrow operator -> is used to dereference variables and call
methods. For methods, it means "pass the thing on the left as the first argument
to the thing on the right."
Objects
An object is a reference that has been blessed into a package.
my %hash = ( foo => 123 );
my $object = bless( \%hash, 'MyClass' );
See code/weather.pl and code/Weather.pm
Methods
A method is a subroutine defined within a package and designed to be invoked (called)
by objects. A method expects the object or the class name as its first argument.
package MyClass;
sub my_method {
my $self = shift(@_); # $self == $object
}
my $object = bless( {}, 'MyClass' );
$object->my_method();
Encapsulation
What's mine is mine, what's yours is yours.
What happens in Vegas, stays in Vegas.
Variables and methods belong to only one package (class) at a time.
A pattern, not a rule.
Inheritance
- UNIVERSAL - all classes inherit from this class
- SUPER - used to call a method in a parent (super)class.
- @ISA - reserved array variable holds the names of all superclasses.
See code/storm.pl.
Polymorphism
A method is said to be polymorphic if its behavior changes based
on the types and/or numbers of arguments passed to it. This includes especially
the calling object.
In Perl, all methods are polymorphic (no strict method signatures).