Introduction to Object Oriented Perl

Peter Karman

http://peknet.com/slides/perl-oo-tut/

What we'll cover

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

Conventions

Packages

A package is a namespace for subroutines and variables. In Perl, a class and a package are the same thing.
     package MyClass;
     
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();
      

Reserved method names

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

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).

Further Reading