Perl Modules

There is a lot more to Perl than what we’re able to show you in this book, and there are a lot of people doing a lot of interesting things with Perl. If there is a problem to solve, then somebody has probably already solved it and made their solution available on the Comprehensive Perl Archive Network (CPAN), which is a worldwide collection of servers and mirrors containing thousands of modules of reusable Perl code.

Finding Modules

Modules come in two types: those that come with Perl and that you should have avail- able to you, and those that you can get from CPAN to install yourself. Unless we say otherwise, the modules that we discuss come with Perl.

To find modules that don’t come with Perl, start at either CPAN Search (http://search.cpan.org/) or Kobes’ Search (http://kobesearch.cpan.org/).* You can browse through the categories or search directly.

Before you go looking for a module, you should check whether it is already installed. One way is to just try to read the documentation with perldoc. The CGI.pm module comes with Perl (and we’ll discuss it later in this chapter), so you should be able to read its documentation:

perldoc CGI

Installing Modules

When you want to install a module that you don’t already have, sometimes you can simply download the distribution, unpack it, and run a series of commands from the shell. Check for a README or INSTALL file that gives you more information. If the module uses MakeMaker, the sequence will be something like this:


$ perl Makefile.PL 

$ make install

If you can’t install modules in the system-wide directories, you can specify another directory with a PREFIX argument to Makefile.PL:


$ perl Makefile.PL PREFIX=/Users/fred/lib

Some Perl module authors use another module, Module::Build, to build and install their creations. That sequence will be something like this:


$ perl Build.PL
$ ./Build install

Some modules depend on other modules though, and they won’t work unless you install yet more modules. Instead of doing all that work ourselves, we can use one of the modules that comes with Perl, CPAN.pm. From the command line, you can start up the CPAN.pm, from which you can issue commands:


$ perl -MCPAN -e shell

Even this can be a little complicated, so a while ago one of our authors wrote a little script called “cpan,” which also comes with Perl and is usually installed with perl and its tools. Just call the script with a list of the modules you want to install:


$ cpan Module::CoreList LWP CGI::Prototype

You might be saying, “But I don’t have a command line!” If you are using the ActiveState port of Perl (for Windows, Linux, or Solaris), you can use the Perl Package Manager (PPM), which installs modules for you. You can even get the ActiveState ports on CD or DVD. Besides what you’ve seen so far, your particular operating system may have ways to install software, including Perl modules.

Using Simple Modules

The File::Basename Module

use File::Basename;

my $name = "/usr/local/bin/perl";
my $basename = basename $name; # gives 'perl'

Using Only Some Functions from a Module

Suppose you discovered that when you went to add the File::Basename module to your existing program, you already have a subroutine called &dirname—that is, you already have a subroutine with the same name as one of the module’s functions. Now there’s trouble because the new dirname is also implemented as a Perl subroutine (inside the module). What do you do?

Simply give File::Basename, in your use declaration, an import list showing exactly which function names it should give you, and it’ll supply those and no others. Here, we’ll get nothing but basename:


use File::Basename qw / basename /;

And here, we'll ask for no new functions as all:


use File::Basename qw/ /;

This is also frequently written as:


use File::Basename ();

Why would you want to do that? Well, this directive tells Perl to load File::Base name, just as before, but not to import any function names. Importing lets us use the short, simple function names like basename and dirname. But even if we don’t import those names, we can still use the functions. When they’re not imported, though, we have to call them by their full names:


use File::Basename qw/ /; # import no function names
my $betty = &dirname($wilma); # uses our own subroutine &dirname #(not shown)
my $name = "/usr/local/bin/perl";
my $dirname = File::Basename::dirname $name; # dirname from the module

As you can see, the full name of the dirname function from the module is File::Base name::dirname. We can always use the function’s full name (once we’ve loaded the module) whether we’ve imported the short name dirname or not.

The File::Spec Module

Now you can find out a file’s basename. That’s useful, but you’ll often want to put that together with a directory name to get a full filename. For example, here we want to take a filename like /home/rootbeer/ice-2.1.txt and add a prefix to the basename:


use File::Basename;


print "Please enter a filename: "; 

chomp(my $old_name = <STDIN>);


my $dirname = dirname $old_name; 

my $basename = basename $old_name;


$basename =~ s/^/not/; # Add a prefix to the basename 

my $new_name = "$dirname/$basename";


rename($old_name, $new_name)
    or warn "Can't rename '$old_name' to '$new_name': $!";

Once again, we’re making the assumption that filenames will follow the Unix conventions and use a forward slash between the directory name and the basename. Fortunately, Perl comes with a module to help with this problem, too.

The File::Spec module is used for manipulating file specifications, which are the names of files, directories, and the other things that are stored on filesystems. Like File::Base name, it understands what kind of system it’s running on, and it chooses the right set of rules every time. But unlike File::Basename, File::Spec is an object-oriented (often abbreviated OO) module.

In this case, we learn from reading the documentation for File::Spec that we want to use a method called catfile. What’s a method? It’s just a different kind of function, as far as we’re concerned here. The difference is that you’ll always call the methods from File::Spec with their full names, like this:


use File::Spec;
.
print "Please enter a filename: "; 

chomp(my $old_name = <STDIN>);


my $dirname = dirname $old_name; 

my $basename = basename $old_name;


$basename =~ s/^/not/; # Add a prefix to the basename 


my $new_name = File::Spec->catfile($dirname, $basename);

rename($old_name, $new_name)
or warn "Can't rename '$old_name' to '$new_name': $!";

As you can see, the full name of a method is the name of the module (called a class here), a small arrow (->) and the short name of the method.

Since we’re calling the method by its full name, though, what symbols does the module import? None of them. That’s normal for OO modules. So you don’t have to worry about having a subroutine with the same name as one of the many methods of File::Spec.

CGI.pm
Databases and DBI

The DBI (Database Interface) module doesn’t come with Perl, but it’s one of the most popular modules since most people have to connect to a database of some sort. The beauty of DBI is that it allows you to use the same interface for just about any common database, from simple comma-separated value files to big database servers like Oracle. It has ODBC drivers, and some of its drivers are even vendor supported. To get the full details, get Programming the Perl DBI by Alligator Descartes and Tim Bunce (O’Reilly). You can also check out the DBI web site at http://dbi.perl.org/.

Once you install DBI, you also have to install a DBD (Database Driver). You can get a long list of DBDs from CPAN Search. Install the right one for your database server, and ensure that you get the version that goes with the version of your server.

The DBI is an object-oriented module, but you don’t have to know everything about OO programming to use it. You just have to follow the examples in the documentation. To connect to a database, you use the DBI module, then call its connect method:


use DBI;
$dbh = DBI->connect($data_source, $username, $password);

The (data_source contains information particular to the DBD that you want to use, so you’ll get that from the DBD. For PostgreSQL, the driver is DBD::Pg, and the )data_source is something like:


my $data_source = "dbi:Pg:dbname=name_of_database";

Once you connect to the database, you go through a cycle of preparing, executing, and reading queries.


$sth = $dbh->prepare("SELECT * FROM foo WHERE bla"); 

$sth->execute();
@row_ary = $sth->fetchrow_array;
$sth->finish;

When you are finished, you disconnect from the database.


$dbh->disconnect();

发表评论

邮箱地址不会被公开。 必填项已用*标注