Perl Information Center Tutorials - Modules
These tutorials were written to help you get a quick, but thorough, understanding of Perl -
the scope of the language as well as it's specific capabilities.
| Beginners
| Built-In Functions
| Advanced
| CGI Applications
|
|
|
|
|
|
Perl Modules
Perl allows you to put subroutines into separate files (called
modules) and to reference those files within a Perl script, making
the subroutines contained within the modules available to the script.
Better yet, Perl ships with other 300 modules, covering a very wide range
of topics. I highly recommend that you review the available modules and
make use of the free code that has been extensively tested by the Perl community.
Also, be sure to visit the website CPAN, the
Comprehensive Perl Archive Network. CPAN contains over 12,000 modules
freely available to Perl programmers.
Module Keywords Summary
There are just a few keywords to know in order to make use of modules.
Add Modules to Scripts
To add a module to a Perl script, you must import the module
with the keyword 'use' as shown in the following code
example.
use mymodule; # content of mymodule.pm is imported
use mymodule.pl; # content of mymodule.pm is imported
If no module filename extension is provided, the default extension of
.pm will be used. Modules installed with Perl all use the file
extension .pm.
Once a module is imported into a script, the subroutines found within
the module can be used/called just as though they were contained within
the script.
Module File Format
A module can be as simple as a standard script file, as in this next
example which contains nothing but two subroutines and a line of code
to return an exit code of 1 (true).
sub lowercase {
$x = shift;
return lc($x);
}
sub mymessage {
print "Gary Beene";
}
1;
Be aware that any code in the module which is outside subroutines will be executed
when the module is imported - such as the last line which is purposely included
because Perl requires that a module return an exit code of 1.
While the simple script file above can be used as a module, most modules contain
significantly more information. For a more complete description of creating modules,
use perldoc.
Using a Module
If the example code above was placed in a file called 'mymodule.pm', then the
following program would execute each of the two subroutines found within the module.
#!/usr/bin/perl
use mymodule;
mymessage; # prints 'Gary Beene'
print lowercase('DOG'); # prints 'dog'
Module Naming
In this simple example, the Perl script and the module would be placed
in the same directory and the module name is simply 'mymodule.pm'.
However, in a typical Perl installation, Perl modules are found in the
'c:\perl\lib' folder, beneath which are found folders that contain the
module *.pm files.
Modules are typically named with the syntax Module::Name, where the
folders beneath 'c:\perl\lib' are the Module and the files themselves
are the Name (less the extension).
In some cases, the folder structure is several levels deep, such as the installed
module File::Spec::Win32, which refers to a module Win32.pm found within the
c:\perl\lib\file\spec folder.
Referencing Module Variables and Subroutines
The File::Find module uses a variable called $dir. To use $dir in a script it can
be referenced as $File::Find::dir.
As long as the 'use' reference to the module occurs at the start of a Perl script
subroutines can be called by simply using the subroutine name (as in the example
script above). However, just as Perl allows the used of an '&' to signify subroutines
further down in the script, subroutines in modules can be referenced early also by using
the '\&' nomenclature, as in '\&mysub'.
Modules Functions/Keywords Reference
Here's a quick reference of the available module functions/keywords, in alphabetical
order.
Unless otherwise noted, these functions operate on $_ by default.
- use - load a module at compile time
no Module VERSION LIST
- no - unimport a module
no Module VERSION LIST
no allows the disabling of a pragma, limited to the code block in which
the no is called.
- package - declare a separate global namespace
package NAMESPACE
package allows compartmentalization of code to prevent the overlapping
use of global variables, particularly when multiple programmers are
working on parts of a project. See perldoc for more information.
- our - declare and assign a package variable
our EXPR
Use of our lets you use module global variables without qualifying
them with package names.
Modules Distributed with Perl
The list of 300+ modules shipped with Perl is provided at the bottom of this
page. Of those, here are some of the more commonly used modules.
- Cwd - get pathname of current working directory
- Fatal - replace functions with equivalents which succeed or die
- File::Basename - parse file paths into directory, filename and suffix.
- File::Copy - copy files or filehandles
- File::Spec - portably perform operations on file names
- Image::Size - read image files sizes (CPAN)
- Net::SMTP - send email using SMTP
- POSIX - advanced math functions
- Sys::Hostname - get PC hostname
- Text::Wrap - line wrapping to form simple paragraphs
- Time::Local - efficiently compute time from local and GMT time
Module Documentation
To learn how to use a particular module contained in the Perl
distribution, enter the following at a command line.
perldoc Module::Name
Pragmatic Modules (Pragmas)
Pragmas are special modules that come with Perl and generally provide
compiler directives.
The following pragmas are distributed with Perl and are documented
within Perldoc. For information on a specific pragma, enter the
following at a command line.
perldoc pragmaname
- attributes - Get/set subroutine or variable attributes
- attrs - Set/get attributes of a subroutine (deprecated)
- autouse - Postpone load of modules until a function is used
- base - Establish IS-A relationship with base classes at compile time
- bigint - Transparent BigInteger support for Perl
- bignum - Transparent BigNumber support for Perl
- bigrat - Transparent BigNumber/BigRational support for Perl
- blib - Use MakeMaker's uninstalled version of a package
- bytes - Force byte semantics rather than character semantics
- charnames - Define character names for \N{named} string literal escapes
- constant - Declare constants
- diagnostics - Produce verbose warning diagnostics
- encoding - Allows you to write your script in non-ascii or non-utf8
- fields - Compile-time class fields
- filetest - Control the filetest permission operators
- if - use a Perl module if a condition holds
- integer - Use integer arithmetic instead of floating point
- less - Request less of something from the compiler
- lib - Manipulate @INC at compile time
- locale - Use and avoid POSIX locales for built-in operations
- open - Set default PerlIO layers for input and output
- ops - Restrict unsafe operations when compiling
- overload - Package for overloading Perl operations
- re - Alter regular expression behaviour
- sigtrap - Enable simple signal handling
- sort - Control sort() behaviour
- strict - Restrict unsafe constructs
- subs - Predeclare sub names
- threads - Perl extension allowing use of interpreter based threads from perl
- threads::shared - Perl extension for sharing data structures between threads
- utf8 - Enable/disable UTF-8 (or UTF-EBCDIC) in source code
- vars - Predeclare global variable names (obsolete)
- vmsish - Control VMS-specific language features
- warnings - Control optional warnings
- warnings::register - Warnings import function
Modules Distributed With Perl
Here is listing of the 300+ modules distributed with Perl.
For more information enter the following at a command line.
perldoc Module::Name
- AnyDBM_File - provide framework for multiple DBMs
- Attribute::Handlers - Simpler definition of attribute handlers
- AutoLoader - load subroutines only on demand
- AutoSplit - split a package for autoloading
- B - The Perl Compiler
- B::Asmdata - Autogenerated data about Perl ops, used to generate bytecode
- B::Assembler - Assemble Perl bytecode
- B::Bblock - Walk basic blocks
- B::Bytecode - Perl compiler's bytecode backend
- B::C - Perl compiler's C backend
- B::CC - Perl compiler's optimized C translation backend
- B::Concise - Walk Perl syntax tree, printing concise info about ops
- B::Debug - Walk Perl syntax tree, printing debug info about ops
- B::Deparse - Perl compiler backend to produce perl code
- B::Disassembler - Disassemble Perl bytecode
- B::Lint - Perl lint
- B::Showlex - Show lexical variables used in functions or files
- B::Stackobj - Helper module for CC backend
- B::Stash - show what stashes are loaded
- B::Terse - Walk Perl syntax tree, printing terse info about ops
- B::Xref - Generates cross reference reports for Perl programs
- Benchmark - benchmark running times of Perl code
- ByteLoader - load byte compiled perl code
- Carp - warn of errors (from perspective of caller)
- Carp::Heavy - heavy machinery, no user serviceable parts inside
- CGI - Simple Common Gateway Interface Class
- CGI::Apache - Backward compatibility module for CGI.pm
- CGI::Carp - CGI routines for writing to the HTTPD (or other) error log
- CGI::Cookie - Interface to Netscape Cookies
- CGI::Fast - CGI Interface for Fast CGI
- CGI::Pretty - module to produce nicely formatted HTML code
- CGI::Push - Simple Interface to Server Push
- CGI::Switch - Backward compatibility module for defunct CGI::Switch
- CGI::Util - Internal utilities used by CGI module
- Class::ISA - report the search path for a class's ISA tree
- Class::Struct - declare struct-like datatypes as Perl classes
- CPAN - query, download and build perl modules from CPAN sites
- CPAN::FirstTime - Utility for CPAN::Config file Initialization
- CPAN::Nox - Wrapper around CPAN.pm without using any XS module
- Cwd - get pathname of current working directory
- Data::Dumper - stringified perl data structures, suitable for both printing and eval
- DB - programmatic interface to the Perl debugging API (draft, subject to change)
- DB_File - Perl5 access to Berkeley DB version 1.x
- DBM_Filter - Filter DBM keys/values
- DBM_Filter::compress -
- DBM_Filter::encode -
- DBM_Filter::int32 -
- DBM_Filter::null -
- DBM_Filter::utf8 -
- Devel::DProf - a Perl code profiler
- Devel::Peek - A data debugging tool for the XS programmer
- Devel::PPPort - Perl/Pollution/Portability
- Devel::SelfStubber - generate stubs for a SelfLoading module
- Digest - Modules that calculate message digests
- Digest::base - Digest base class
- Digest::file - Calculate digests of files
- Digest::MD5 - Perl interface to the MD5 Algorithm
- DirHandle - supply object methods for directory handles
- Dumpvalue - provides screen dump of Perl data.
- DynaLoader - Dynamically load C libraries into Perl code
- Encode - character encodings
- Encode::Alias - alias definitions to encodings
- Encode::Byte - Single Byte Encodings
- Encode::CJKConstants - Internally used by Encode::??::ISO_2022_*
- Encode::CN - China-based Chinese Encodings
- Encode::CN::HZ - internally used by Encode::CN
- Encode::Config - internally used by Encode
- Encode::EBCDIC - EBCDIC Encodings
- Encode::Encoder - Object Oriented Encoder
- Encode::Encoding - Encode Implementation Base Class
- Encode::Guess - Guesses encoding from data
- Encode::JP - Japanese Encodings
- Encode::JP::H2Z - internally used by Encode::JP::2022_JP*
- Encode::JP::JIS7 - internally used by Encode::JP
- Encode::KR - Korean Encodings
- Encode::KR::2022_KR - internally used by Encode::KR
- Encode::MIME::Header - MIME 'B' and 'Q' header encoding
- Encode::Symbol - Symbol Encodings
- Encode::TW - Taiwan-based Chinese Encodings
- Encode::Unicode - Various Unicode Transformation Formats
- Encode::Unicode::UTF7 - UTF-7 encoding
- English - use nice English (or awk) names for ugly punctuation variables
- Env - perl module that imports environment variables as scalars or arrays
- Errno - System errno constants
- Exporter - Implements default import method for modules
- Exporter::Heavy - Exporter guts
- ExtUtils::Command - utilities to replace common UNIX commands in Makefiles etc.
- ExtUtils::Command::MM - Commands for the MM's to use in Makefiles
- ExtUtils::Constant - generate XS code to import C header constants
- ExtUtils::Constant::Base - base class for ExtUtils::Constant objects
- ExtUtils::Constant::Utils - helper functions for ExtUtils::Constant
- ExtUtils::Constant::XS - base class for ExtUtils::Constant objects
- ExtUtils::Embed - Utilities for embedding Perl in C/C++ applications
- ExtUtils::Install - install files from here to there
- ExtUtils::Installed - Inventory management of installed modules
- ExtUtils::Liblist - determine libraries to use and how to use them
- ExtUtils::MakeMaker - Create a module Makefile
- ExtUtils::MakeMaker::bytes - Version-agnostic bytes.pm
- ExtUtils::MakeMaker::Config - Wrapper around Config.pm
- ExtUtils::MakeMaker::vmsish - Platform-agnostic vmsish.pm
- ExtUtils::Manifest - utilities to write and check a MANIFEST file
- ExtUtils::Mkbootstrap - make a bootstrap file for use by DynaLoader
- ExtUtils::Mksymlists - write linker options files for dynamic extension
- ExtUtils::MM - OS adjusted ExtUtils::MakeMaker subclass
- ExtUtils::MM_AIX - AIX specific subclass of ExtUtils::MM_Unix
- ExtUtils::MM_Any - Platform-agnostic MM methods
- ExtUtils::MM_BeOS - methods to override UN*X behaviour in ExtUtils::MakeMaker
- ExtUtils::MM_Cygwin - methods to override UN*X behaviour in ExtUtils::MakeMaker
- ExtUtils::MM_DOS - DOS specific subclass of ExtUtils::MM_Unix
- ExtUtils::MM_MacOS - once produced Makefiles for MacOS Classic
- ExtUtils::MM_NW5 - methods to override UN*X behaviour in ExtUtils::MakeMaker
- ExtUtils::MM_OS2 - methods to override UN*X behaviour in ExtUtils::MakeMaker
- ExtUtils::MM_QNX - QNX specific subclass of ExtUtils::MM_Unix
- ExtUtils::MM_Unix - methods used by ExtUtils::MakeMaker
- ExtUtils::MM_UWIN - U/WIN specific subclass of ExtUtils::MM_Unix
- ExtUtils::MM_VMS - methods to override UN*X behaviour in ExtUtils::MakeMaker
- ExtUtils::MM_VOS - VOS specific subclass of ExtUtils::MM_Unix
- ExtUtils::MM_Win32 - methods to override UN*X behaviour in ExtUtils::MakeMaker
- ExtUtils::MM_Win95 - method to customize MakeMaker for Win9X
- ExtUtils::MY - ExtUtils::MakeMaker subclass for customization
- ExtUtils::Packlist - manage .packlist files
- ExtUtils::testlib - add blib/* directories to @INC
- Fatal - replace functions with equivalents which succeed or die
- Fcntl - load the C Fcntl.h defines
- File::Basename - Parse file paths into directory, filename and suffix.
- File::CheckTree - run many filetest checks on a tree
- File::Compare - Compare files or filehandles
- File::Copy - Copy files or filehandles
- File::DosGlob - DOS like globbing and then some
- File::Find - Traverse a directory tree.
- File::Glob - Perl extension for BSD glob routine
- File::Path - create or remove directory trees
- File::Spec - portably perform operations on file names
- File::Spec::Cygwin - methods for Cygwin file specs
- File::Spec::Epoc - methods for Epoc file specs
- File::Spec::Functions - portably perform operations on file names
- File::Spec::Mac - File::Spec for Mac OS (Classic)
- File::Spec::OS2 - methods for OS/2 file specs
- File::Spec::Unix - File::Spec for Unix, base for other File::Spec modules
- File::Spec::VMS - methods for VMS file specs
- File::Spec::Win32 - methods for Win32 file specs
- File::stat - by-name interface to Perl's built-in stat() functions
- File::Temp - return name and handle of a temporary file safely
- FileCache - keep more files open than the system permits
- FileHandle - supply object methods for filehandles
- Filter::Simple - Simplified source filtering
- Filter::Util::Call - Perl Source Filter Utility Module
- FindBin - Locate directory of original perl script
- Getopt::Long - Extended processing of command line options
- Getopt::Std - Process single-character switches with switch clustering
- Hash::Util - A selection of general-utility hash subroutines
- I18N::Collate - compare 8-bit scalar data according to the current locale
- I18N::Langinfo - query locale information
- I18N::LangTags - functions for dealing with RFC3066-style language tags
- I18N::LangTags::Detect - detect the user's language preferences
- I18N::LangTags::List - tags and names for human languages
- IO - load various IO modules
- IO::Dir - supply object methods for directory handles
- IO::File - supply object methods for filehandles
- IO::Handle - supply object methods for I/O handles
- IO::Pipe - supply object methods for pipes
- IO::Poll - Object interface to system poll call
- IO::Seekable - supply seek based methods for I/O objects
- IO::Select - OO interface to the select system call
- IO::Socket - Object interface to socket communications
- IO::Socket::INET - Object interface for AF_INET domain sockets
- IO::Socket::UNIX - Object interface for AF_UNIX domain sockets
- IPC::Msg - SysV Msg IPC object class
- IPC::Open2 - open a process for both reading and writing
- IPC::Open3 - open a process for reading, writing, and error handling
- IPC::Semaphore - SysV Semaphore IPC object class
- IPC::SysV - SysV IPC constants
- List::Util - A selection of general-utility list subroutines
- Locale::Constants - constants for Locale codes
- Locale::Country - ISO codes for country identification (ISO 3166)
- Locale::Currency - ISO three letter codes for currency identification (ISO 4217)
- Locale::Language - ISO two letter codes for language identification (ISO 639)
- Locale::Maketext - framework for localization
- Locale::Script - ISO codes for script identification (ISO 15924)
- Math::BigFloat - Arbitrary size floating point math package
- Math::BigInt - Arbitrary size integer/float math package
- Math::BigInt::Calc - Pure Perl module to support Math::BigInt
- Math::BigInt::CalcEmu - Emulate low-level math with BigInt code
- Math::BigRat - Arbitrary big rational numbers
- Math::Complex - complex numbers and associated mathematical functions
- Math::Trig - trigonometric functions
- Memoize - Make functions faster by trading space for time
- Memoize::AnyDBM_File - glue to provide EXISTS for AnyDBM_File for Storable use
- Memoize::Expire - Plug-in module for automatic expiration of memoized values
- Memoize::ExpireFile - test for Memoize expiration semantics
- Memoize::ExpireTest - test for Memoize expiration semantics
- Memoize::NDBM_File - glue to provide EXISTS for NDBM_File for Storable use
- Memoize::SDBM_File - glue to provide EXISTS for SDBM_File for Storable use
- Memoize::Storable - store Memoized data in Storable database
- MIME::Base64 - Encoding and decoding of base64 strings
- MIME::QuotedPrint - Encoding and decoding of quoted-printable strings
- NDBM_File - Tied access to ndbm files
- Net::Cmd - Network Command class (as used by FTP, SMTP etc)
- Net::Config - Local configuration data for libnet
- Net::Domain - Attempt to evaluate the current host's internet name and domain
- Net::FTP - FTP Client class
- Net::hostent - by-name interface to Perl's built-in gethost*() functions
- Net::netent - by-name interface to Perl's built-in getnet*() functions
- Net::Netrc - OO interface to users netrc file
- Net::NNTP - NNTP Client class
- Net::Ping - check a remote host for reachability
- Net::POP3 - Post Office Protocol 3 Client class (RFC1939)
- Net::protoent - by-name interface to Perl's built-in getproto*() functions
- Net::servent - by-name interface to Perl's built-in getserv*() functions
- Net::SMTP - Simple Mail Transfer Protocol Client
- Net::Time - time and daytime network client interface
- NEXT - Provide a pseudo-class NEXT (et al) that allows method redispatch
- O - Generic interface to Perl Compiler backends
- Opcode - Disable named opcodes when compiling perl code
- PerlIO - On demand loader for PerlIO layers and root of PerlIO::* name space
- PerlIO::encoding - encoding layer
- PerlIO::scalar - in-memory IO, scalar IO
- PerlIO::via - Helper class for PerlIO layers implemented in perl
- PerlIO::via::QuotedPrint - PerlIO layer for quoted-printable strings
- Pod::Checker - check pod documents for syntax errors
- Pod::Find - find POD documents in directory trees
- Pod::Functions - Group Perl's functions a la perlfunc.pod
- Pod::Html - module to convert pod files to HTML
- Pod::InputObjects - objects representing POD input paragraphs, commands, etc.
- Pod::LaTeX - Convert Pod data to formatted Latex
- Pod::Man - Convert POD data to formatted *roff input
- Pod::ParseLink - Parse an L<> formatting code in POD text
- Pod::Parser - base class for creating POD filters and translators
- Pod::ParseUtils - helpers for POD parsing and conversion
- Pod::Perldoc::ToChecker - let Perldoc check Pod for errors
- Pod::Perldoc::ToMan - let Perldoc render Pod as man pages
- Pod::Perldoc::ToNroff - let Perldoc convert Pod to nroff
- Pod::Perldoc::ToPod - let Perldoc render Pod as ... Pod!
- Pod::Perldoc::ToRtf - let Perldoc render Pod as RTF
- Pod::Perldoc::ToText - let Perldoc render Pod as plaintext
- Pod::Perldoc::ToTk - let Perldoc use Tk::Pod to render Pod
- Pod::Perldoc::ToXml - let Perldoc render Pod as XML
- Pod::Plainer - Perl extension for converting Pod to old style Pod.
- Pod::PlainText - Convert POD data to formatted ASCII text
- Pod::Select - extract selected sections of POD from input
- Pod::Text - Convert POD data to formatted ASCII text
- Pod::Text::Color - Convert POD data to formatted color ASCII text
- Pod::Text::Overstrike - Convert POD data to formatted overstrike text
- Pod::Text::Termcap - Convert POD data to ASCII text with format escapes
- Pod::Usage - print a usage message from embedded pod documentation
- POSIX - Perl interface to IEEE Std 1003.1
- Safe - Compile and execute code in restricted compartments
- Scalar::Util - A selection of general-utility scalar subroutines
- SDBM_File - Tied access to sdbm files
- Search::Dict - search for key in dictionary file
- SelectSaver - save and restore selected file handle
- SelfLoader - load functions only on demand
- Shell - run shell commands transparently within perl
- Socket - load the C socket.h defines and structure manipulators
- Storable - persistence for Perl data structures
- Switch - A switch statement for Perl
- Symbol - manipulate Perl symbols and their names
- Sys::Hostname - Try every conceivable way to get hostname
- Sys::Syslog - Perl interface to the UNIX syslog(3) calls
- Term::ANSIColor - Color screen output using ANSI escape sequences
- Term::Cap - Perl termcap interface
- Term::Complete - Perl word completion module
- Term::ReadLine - Perl interface to various readline packages. If no real package is found, substitutes stubs instead of basic functions.
- Test - provides a simple framework for writing test scripts
- Test::Builder - Backend for building test libraries
- Test::Builder::Module - Base class for test modules
- Test::Builder::Tester - test testsuites that have been built with Test::Builder
- Test::Builder::Tester::Color - turn on colour in Test::Builder::Tester
- Test::Harness - Run Perl standard test scripts with statistics
- Test::Harness::Assert - simple assert
- Test::Harness::Iterator - Internal Test::Harness Iterator
- Test::Harness::Point - object for tracking a single test point
- Test::Harness::Straps - detailed analysis of test results
- Test::More - yet another framework for writing test scripts
- Test::Simple - Basic utilities for writing tests.
- Text::Abbrev - create an abbreviation table from a list
- Text::Balanced - Extract delimited text sequences from strings.
- Text::ParseWords - parse text into an array of tokens or array of arrays
- Text::Soundex - Implementation of the Soundex Algorithm as Described by Knuth
- Text::Tabs - expand and unexpand tabs per the unix expand(1) and unexpand(1)
- Text::Wrap - line wrapping to form simple paragraphs
- Thread - manipulate threads in Perl (for old code only)
- Thread::Queue - thread-safe queues
- Thread::Semaphore - thread-safe semaphores
- Tie::Array - base class for tied arrays
- Tie::File - Access the lines of a disk file via a Perl array
- Tie::Handle - base class definitions for tied handles
- Tie::Hash - base class definitions for tied hashes
- Tie::Memoize - add data to hash when needed
- Tie::RefHash - use references as hash keys
- Tie::Scalar - base class definitions for tied scalars
- Tie::SubstrHash - Fixed-table-size, fixed-key-length hashing
- Time::gmtime - by-name interface to Perl's built-in gmtime() function
- Time::HiRes - High resolution alarm, sleep, gettimeofday, interval timers
- Time::Local - efficiently compute time from local and GMT time
- Time::localtime - by-name interface to Perl's built-in localtime() function
- Time::tm - internal object used by Time::gmtime and Time::localtime
- Unicode::Collate - Unicode Collation Algorithm
- Unicode::Normalize - Unicode Normalization Forms
- Unicode::UCD - Unicode character database
- UNIVERSAL - base class for ALL classes (blessed references)
- User::grent - by-name interface to Perl's built-in getgr*() functions
- User::pwent - by-name interface to Perl's built-in getpw*() functions
- XS::APItest - Test the perl C API
- XS::Typemap - module to test the XS typemaps distributed with perl
- XSLoader - Dynamically load C libraries into Perl code
If you have any suggestions for additions to these tutorials, please let me know.
|