introduction to Perl 5 for web developers Using Modules To use a module, all you need to do is use the "use" keyword. For example to use the Cat module, you would use the following line in your program:

     use Cat;

Here we have a module called Cat.pm

     package Cat;
     sub new {
        my $class = shift;
        my $self = {};
        bless $self;
        if (defined $_[0]) {
                $self->{'name'} = shift;
                }
        if (defined $_[0]) {
                $self->{'color'} = shift;
                }
        return $self;
      }

     sub meow {
        my $self = shift;
        print "meow\n";
      }

     sub printDetails {
        my $self = shift;
        print "$self->{name}\n";
        print "$self->{color}\n";
     }

     1;

Let's use Cat.pm in a program called test.pl

     #!/usr/bin/perl -wT

     use strict;
     use Cat;

     my $cat = new Cat("Fred", "white");
     $cat->meow();

Note that "use" is the Perl 5-ish way to load modules into Perl memory. However, you may also make use of the old Perl 4 require command to do the same thing.

The main difference between use and require is that use does a few more things for you.

First, use loads all the modules at compile-time when the program is first loaded and so the run-time efficiency of the program is not effected by use and if a module is missing you will know immediately upon running the program rather than find out that a module is missing when your program finally gets around to "require"ing it.

Second, the use statement also calls an export() routine that can optionally take methods inside the package and export them to your local name space. This is useful because you can export standalone methods so that they can be called conveniently in your program without constantly qualifying them with the package name or an object reference.

There are an incredible number of modules out there for you to use at archives such as CPAN.

In fact, the best way to go about practicing using modules is to go out and find some that you need. The fact is that there is probably a Perl module already written for all of the simple to complex tasks you will need for 98% of your projects. There is even a searchable CPAN archive. You needn't write the code yourself cause it has already been written!

Previous | Next | Table of Contents