Object-Oriented Modules

Some modules are object-oriented. Instead of importing a series of subroutines that are called directly, these modules define a series of object types that you can create and use. We will talk about object-oriented syntax in greater detail in the Perl References and Objects lecture. Here we will just show an example:

The Math::Complex Module

The Math::Complex module is a standard module that implements complex numbers. You work with it by creating one or more Math::Complex objects. You can then manipulate these objects mathematically by adding them, subtracting them, multiplying, and so on. Here is a brief example:

#!/usr/bin/perl
# file: complex.pl

use strict;
use Math::Complex;

my $a = Math::Complex->make(5,6);
my $b = Math::Complex->make(10,20);
my $c = $a * $b;

print "$a * $b = $c\n";

We load the Math::Complex module with use, but now instead of calling imported subroutines, we create two objects named $a and $b. Both are created by calling Math::Complex->make() with two arguments. The first argument is the real part of the complex number, and the second is the imaginary part. The return value from make() is the complex number object. We multiply the two numbers together and store the result in $c. Finally, we print out all three values. The script's output is:

51% perl complex.pl
5+6i * 10+20i = -70+160i

Object Syntax

The call to make() uses Perl's object-oriented syntax. Read it as meaning "invoke the make() subroutine that is located inside the Math::Complex package." The call is similar, but not quite equivalent, to this:

Math::Complex::make(10,20)

The difference is that the object-oriented syntax tells Perl to pass the name of the module as an implicit first argument to make(). Therefore, Math::Complex->make(10,20) is almost exactly equivalent to this:

Math::Complex::make('Math::Complex',10,20)

If you are using object-oriented modules, you will never have to worry about this extra argument. If you are writing object-oriented modules, the necessity for the extra argument will make sense to you.


<< Previous
Contents >> Next >>

Lincoln D. Stein, lstein@cshl.org
Cold Spring Harbor Laboratory
Last modified: Wed Oct 23 14:50:40 EDT 2002