CARVIEW |
Select Language
HTTP/2 302
server: nginx
date: Wed, 20 Aug 2025 23:49:52 GMT
content-type: text/plain; charset=utf-8
content-length: 0
x-archive-redirect-reason: found capture at 20080212084356
location: https://web.archive.org/web/20080212084356/https://www.oreilly.com/catalog/perlnut/toc.html
server-timing: captures_list;dur=0.469455, exclusion.robots;dur=0.019176, exclusion.robots.policy;dur=0.009052, esindex;dur=0.011019, cdx.remote;dur=28.657125, LoadShardBlock;dur=1254.597971, PetaboxLoader3.datanode;dur=861.668462, PetaboxLoader3.resolve;dur=176.631650
x-app-server: wwwb-app225
x-ts: 302
x-tr: 1304
server-timing: TR;dur=0,Tw;dur=0,Tc;dur=0
set-cookie: wb-p-SERVER=wwwb-app225; path=/
x-location: All
x-rl: 0
x-na: 0
x-page-cache: MISS
server-timing: MISS
x-nid: DigitalOcean
referrer-policy: no-referrer-when-downgrade
permissions-policy: interest-cohort=()
HTTP/2 200
server: nginx
date: Wed, 20 Aug 2025 23:49:53 GMT
content-type: text/html
x-archive-orig-date: Tue, 12 Feb 2008 08:43:55 GMT
x-archive-orig-server: Apache
x-archive-orig-p3p: policyref="https://www.oreillynet.com/w3c/p3p.xml",CP="CAO DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONo OUR DELa PUBi OTRa IND PHY ONL UNI PUR COM NAV INT DEM CNT STA PRE"
x-archive-orig-last-modified: Wed, 06 Feb 2008 10:42:13 GMT
x-archive-orig-accept-ranges: bytes
x-archive-orig-content-length: 1251168
x-archive-orig-x-cache: MISS from oregano.bp
x-archive-orig-x-cache-lookup: MISS from oregano.bp:3128
x-archive-orig-via: 1.0 oregano.bp:3128 (squid/2.6.STABLE12)
x-archive-orig-connection: close
x-archive-guessed-content-type: text/html
x-archive-guessed-charset: utf-8
memento-datetime: Tue, 12 Feb 2008 08:43:56 GMT
link: ; rel="original", ; rel="timemap"; type="application/link-format", ; rel="timegate", ; rel="first memento"; datetime="Thu, 29 Apr 1999 10:48:22 GMT", ; rel="prev memento"; datetime="Fri, 11 Jan 2008 06:59:43 GMT", ; rel="memento"; datetime="Tue, 12 Feb 2008 08:43:56 GMT", ; rel="next memento"; datetime="Fri, 14 Mar 2008 03:01:24 GMT", ; rel="last memento"; datetime="Thu, 06 Jun 2024 07:13:34 GMT"
content-security-policy: default-src 'self' 'unsafe-eval' 'unsafe-inline' data: blob: archive.org web.archive.org web-static.archive.org wayback-api.archive.org athena.archive.org analytics.archive.org pragma.archivelab.org wwwb-events.archive.org
x-archive-src: 51_2_20080212083137_crawl104-c/51_2_20080212084145_crawl100.arc.gz
server-timing: captures_list;dur=0.574270, exclusion.robots;dur=0.020349, exclusion.robots.policy;dur=0.009984, esindex;dur=0.012150, cdx.remote;dur=20.269323, LoadShardBlock;dur=129.780976, PetaboxLoader3.datanode;dur=134.072559, PetaboxLoader3.resolve;dur=128.588682, load_resource;dur=156.079879
x-app-server: wwwb-app225
x-ts: 200
x-tr: 1001
server-timing: TR;dur=0,Tw;dur=0,Tc;dur=0
x-location: All
x-rl: 0
x-na: 0
x-page-cache: MISS
server-timing: MISS
x-nid: DigitalOcean
referrer-policy: no-referrer-when-downgrade
permissions-policy: interest-cohort=()
content-encoding: gzip
O'Reilly Media | Perl in a Nutshell
Buy this Book
Read it Now!
Reprint Licensing

--
Please select a chapter from the Table of Contents and click the button above to begin the licensing process.
Perl in a Nutshell
By Stephen Spainhour, Ellen Siever, Nathan Patwardhan
Cover | Table of Contents | Colophon
Table of Contents
- Chapter 1: Introduction to Perl
- Content preview·Buy reprint rights for this chapterComputer languages differ not so much in what they make possible, but in what they make easy. Perl is designed to make the easy jobs easy, without making the hard jobs impossible. Perl makes it easy to manipulate numbers, text, files, directories, computers, networks, and programs. It also makes it easy to develop, modify, and debug your own programs portably, on any modern operating system.Perl is especially popular with systems programmers and web developers, but it also appeals to a much broader audience. Originally designed for text processing, it has grown into a sophisticated, general-purpose programming language with a rich software development environment complete with debuggers, profilers, cross-referencers, compilers, interpreters, libraries, syntax-directed editors, and all the rest of the trappings of a "real" programming language.There are many reasons for Perl's success. For starters, Perl is freely available and freely redistributable. But that's not enough to explain the Perl phenomenon, since many other freeware packages fail to thrive. Perl is not just free; it's also fun. People feel like they can be creative in Perl, because they have freedom of expression.Perl is both a very simple language and a very rich language. It's a simple language in that the types and structures are simple to use and understand, and it borrows heavily from other languages you may already be familiar with. You don't have to know everything there is to know about Perl before you can write useful programs.However, Perl is also a rich language, and there is much to learn about it. That's the price of making hard things possible. Although it will take some time for you to absorb all that Perl can do, somewhere down the line you will be glad that you have access to the extensive capabilities of Perl.Perl has the advantage of being easy to learn if you just want to write simple scripts—thus its appeal to the ever-impatient system administrator and the deadline-driven CGI developer. However, as you become more ambitious, Perl lets you act on those ambitions. Chapter 2, covers how to get and install Perl, and Chapter 3, through Chapter 6, cover the basics of the Perl language, its functions, and how to use the Perl debugger.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - What's Perl Good For?
- Content preview·Buy reprint rights for this chapterPerl has the advantage of being easy to learn if you just want to write simple scripts—thus its appeal to the ever-impatient system administrator and the deadline-driven CGI developer. However, as you become more ambitious, Perl lets you act on those ambitions. Chapter 2, covers how to get and install Perl, and Chapter 3, through Chapter 6, cover the basics of the Perl language, its functions, and how to use the Perl debugger.On top of the Perl language itself, however, are the Perl modules. You can think of modules as add-ons to the Perl language that allow you to streamline tasks by providing a consistent API. Perl itself is fun to use, but the modules lend Perl even more flexibility and enormous power. Furthermore, anyone can write and distribute a Perl module. Some modules are deemed important enough or popular enough to be distributed with Perl itself, but very few are actually written by the core Perl developers themselves. Chapter 7, introduces you to Perl modules, and Chapter 8, covers the standard modules that are distributed with Perl itself.The most popular Perl module is CGI.pm, which gives a simple interface to developing CGI (common gateway interface) applications in Perl. While Perl itself is indispensable for many different tasks, its text-manipulation features make it perfect for CGI development on the Web. In fact, the resurgence of Perl over the past few years must be credited to its popularity as a CGI language. Chapter 10, and Chapter 11, talk about using Perl for CGI, including mod_perl, which merges Perl into the Apache web server.Database interconnectivity is one of the most important functions of any programming language today, and Perl is no exception. DBI is a suite of modules that provide a consistent database-independent interface for Perl. Chapter 12, covers both DBI and DBM (the more primitive but surprisingly effective database interface built directly into Perl).The Internet doesn't start and stop at CGI. Network programming is another of Perl's strengths, with a robust sockets interface and several modules for writing clients and servers for all sorts of Internet services—not only the Web, but also email, news, FTP, etc. Chapter 13, through Chapter 17, cover the modules for developing fully functional Internet applications in Perl.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Perl Development
- Content preview·Buy reprint rights for this chapterSoftware doesn't grow on trees. Perl is free because of the donated efforts of several generous persons who have devoted large chunks of their spare time to the development, maintenance, and evangelism of Perl.Perl itself was created by Larry Wall, in an effort to produce reports for a bug-reporting system. Larry designed a new scripting language for this purpose, and then released it to the Internet, thinking that someone else might find it useful. In the spirit of freeware, other people suggested improvements and even ways to implement them, and Perl transformed from a cute scripting language into a robust programming language.Today, Larry does little actual development himself, but he is the ringleader of a core development team known as the Perl Porters. The Porters determine which new features should be added and which pesky bugs should be fixed. To keep it from being a free-for-all, there is generally one person who is responsible for delivering the next release of Perl, with several "development releases" in the interim.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Which Platforms Support Perl?
- Content preview·Buy reprint rights for this chapterWhile Perl was developed on Unix and is closely entwined with Unix culture, it also has a strong following on the Windows and Macintosh platforms. Perl gives Windows 95, Windows NT, Macintosh, and even VMS users the opportunity to take advantage of the scripting power that Unix users take for granted.Most Unix machines will have Perl already installed, since it's one of the first things a Unix system administrator will build for a new machine (and is in fact distributed with the operating system on some versions of Unix, such as Linux and FreeBSD). For Windows NT, Windows 95, and Macintosh, there are binary distributions of Perl that you can download for free. See Chapter 2 for information on installing Perl.Although there is some history of other platforms not being treated seriously by the Perl community, Perl is becoming increasingly friendly to non-Unix platforms. The Win32 ports of Perl are quite stable, and as of Perl 5.005, are integrated wholly with core Perl. MacPerl integration is expected with Perl 5.006.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Perl Resources
- Content preview·Buy reprint rights for this chapterParadoxically, the way in which Perl helps you the most has almost nothing to do with Perl itself, and everything to do with the people who use Perl. While people start using Perl because they need it, they continue using Perl because they love it.The result is that the Perl community is one of the most helpful in the world. When Perl programmers aren't writing their own programs, they spend their time helping others write theirs. They discuss common problems and help devise solutions. They develop utilities and modules for Perl, and give them away to the world at large.The central meeting place for Perl aficionados is Usenet. If you're not familiar with Usenet, it's a collection of special-interest groups (called newsgroups) on the Internet. For most anyone using a modern browser, Usenet access is as simple as a selecting a menu option on the browser. Perl programmers should consider subscribing to the following newsgroups:
-
comp.lang.perl.announce
-
A moderated newsgroup with announcements about new utilities or products related to Perl.
-
comp.lang.perl.misc
-
The general-purpose newsgroup devoted to non-CGI-related Perl programming questions.
-
comp.lang.perl.moderated
-
A moderated newsgroup intended to be a forum for more controlled, restrained discussions about Perl.
-
comp.lang.perl.modules
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Chapter 2: Installing Perl
- Content preview·Buy reprint rights for this chapterThe best things in life are free. So is Perl. Although you can get a bundled Perl distribution on CD-ROM, most people download Perl from an online archive. CPAN, the Comprehensive Perl Archive Network, is the main distribution point for all things Perl. Whether you are looking for Perl itself, for a module, or for documentation about Perl, CPAN is the place to go, at
https://www.perl.com/CPAN/
. The ongoing development and enhancement of Perl is very much a cooperative effort, and CPAN is the place where the work of many individuals comes together.CPAN represents the development interests of a cross-section of the Perl community. It contains Perl utilities, modules, documentation, and (of course) the Perl distribution itself. CPAN was created by Jarkko Hietaniemi and Andreas König.The home system for CPAN is funet.fi, but CPAN is also mirrored on many other sites around the globe. This ensures that anyone with an Internet connection can have reliable access to CPAN's contents at any time. Since the structure of all CPAN sites is the same, a user searching for the current version of Perl can be sure that the latest.tar.gz file is the same on every site.The easiest way to access CPAN is to utilize the CPAN multiplex service atwww.perl.com
. The multiplexor tries to connect you to a local, fast machine on a large bandwidth hub. To use the multiplexor, go tohttps://www.perl.com/CPAN/
; the multiplexor will automatically route you to a site based on your domain.If you prefer, you can choose a particular CPAN site, instead of letting the multiplexor choose one for you. To do that, go to the URLhttps://www.perl.com/CPAN
(no trailing slash). When you omit the trailing slash, the CPAN multiplexor presents a menu of CPAN mirrors from which you select the one you want. It remembers your choice next time.If you want to use anonymous FTP, the following machines should have the Perl source code plus a copy of the CPAN mirror list:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The CPAN Architecture
- Content preview·Buy reprint rights for this chapterCPAN represents the development interests of a cross-section of the Perl community. It contains Perl utilities, modules, documentation, and (of course) the Perl distribution itself. CPAN was created by Jarkko Hietaniemi and Andreas König.The home system for CPAN is funet.fi, but CPAN is also mirrored on many other sites around the globe. This ensures that anyone with an Internet connection can have reliable access to CPAN's contents at any time. Since the structure of all CPAN sites is the same, a user searching for the current version of Perl can be sure that the latest.tar.gz file is the same on every site.The easiest way to access CPAN is to utilize the CPAN multiplex service at
www.perl.com
. The multiplexor tries to connect you to a local, fast machine on a large bandwidth hub. To use the multiplexor, go tohttps://www.perl.com/CPAN/
; the multiplexor will automatically route you to a site based on your domain.If you prefer, you can choose a particular CPAN site, instead of letting the multiplexor choose one for you. To do that, go to the URLhttps://www.perl.com/CPAN
(no trailing slash). When you omit the trailing slash, the CPAN multiplexor presents a menu of CPAN mirrors from which you select the one you want. It remembers your choice next time.If you want to use anonymous FTP, the following machines should have the Perl source code plus a copy of the CPAN mirror list:ftp.perl.com
ftp.cs.colorado.edu
ftp.cise.ufl.edu
ftp.funet.fi
ftp.cs.ruu.nl
The location of the top directory of the CPAN mirror differs on these machines, so look around once you get there. It's often something like /pub/perl/CPAN.If you don't have reliable Internet access, you can also get CPAN on CD as part of O'Reilly'sAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - How Is CPAN Organized?
- Content preview·Buy reprint rights for this chapterCPAN materials are grouped into categories, including Perl modules, distributions, documentation, announcements, ports, scripts, and contributing authors. Each category is linked to related categories. For example, links to a graphing module written by an author appear in both the module and the author areas.Since CPAN provides the same offerings worldwide, the directory structure has been standardized; files are located in the same place in the directory hierarchy at all CPAN sites. All CPAN sites use CPAN as the root directory, from which the user can select a specific Perl item.From the CPAN directory you have the following choices:
CPAN.html CPAN info page; lists what's available in CPAN and describes each of the modules ENDINGS Description of the file extensions, such as .tar, .gz, and .zip MIRRORED BY A list of sites mirroring CPAN MIRRORING.FROM A list of sites mirrored by CPAN README A brief description of what you'll find on CPAN README.html An HTML-formatted version of the README file RECENT Recent additions to the CPAN site RECENT.DAY Recent additions to the CPAN site (daily) RECENT.html An HTML-formatted list of recent additions RECENT.WEEK Recent additions to the CPAN site (weekly) ROADMAP What you'll find on CPAN and where ROADMAP.html An HTML-formatted version of ROADMAP SITES An exhaustive list of CPAN sites SITES.html An HTML-formatted version of SITES authors A list of CPAN authors clpa An archive of comp.lang.perl.announce doc Various Perl documentation, FAQs, etc. indices All that is indexed. latest.tar.gz The latest Perl distribution sources misc Misc Perl stuff like Larry Wall quotes and gifs modules Modules for Perl version 5 other-archives Other things yet uncategorized ports Various Perl ports scripts Various scripts appearing in Perl books src The Perl sources from various versions
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Installing Perl
- Content preview·Buy reprint rights for this chapterMost likely your system administrator is responsible for installing and upgrading Perl. But if you are the system administrator, or you want to install Perl on your own system, sooner or later you will find yourself installing a new version of Perl.If you have been running Perl, and you are now going to install Perl 5.005, you need to be aware that it is not binary-compatible with older versions. This means that you must rebuild and reinstall any dynamically loaded extensions that you built under earlier versions.Specific installation instructions come in the README and INSTALL files of the Perl distribution kit. If you don't already have the Perl distribution, you can download it from CPAN—the latest Unix distribution is in latest.tar.gz. The information in this section is an overview of the installation process. The gory details are in the INSTALL file, which you should look at before starting, especially if you haven't done an installation before. Note that operating systems other than Unix may have special instructions; if so, follow those instructions instead of what's in this section or in INSTALL. Look for a file named README.xxx, where xxx is your OS name.In addition to Perl itself, the standard distribution includes a set of core modules that are automatically installed with Perl. See Section 2.4 later in this chapter for how to install modules that are not bundled with Perl; Chapter 8, describes the standard modules in some detail.Typically, you'll get the Perl kit packed as either a tar file or as a set of shar (shell archive) scripts; in either case, the file will be in a compressed format. If you got your version of Perl directly from CPAN, it is probably in "tar-gzipped" format; tar and gzip are popular Unix data-archiving formats. In any case, once you've downloaded the distribution, you need to uncompress and unpack it. The filename indicates what kind of compression was used. AAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Getting and Installing Modules
- Content preview·Buy reprint rights for this chapterAs you'll see when you look at the lists of modules and their authors on CPAN, many users have made their modules freely available. If you find an interesting problem and are thinking of writing a module to solve it, check the modules directory on CPAN first to see if there is a module there that you can use. The chances are good that there is either a module already that does what you need, or perhaps one that you can extend, rather than starting from scratch.Before you download a module, you might also check your system to see if it's already installed. The following command searches the libraries in the
@INC
array and prints the names of all modules it finds:find `perl -e 'print "@INC"'` -name '*.pm' -print
If you start from the modules directory on CPAN, you'll see that the modules are categorized into three subdirectories:by-authors Modules by author's registered CPAN name by-category Modules by subject matter (see below) by-module Modules by namespace (i.e., MIME)
If you know what module you want, you can go directly to it by clicking on the by-module entry. If you are looking for a module in a particular category, you can find it through the by-category subdirectory. If you know the author, click on by-author. However, if you aren't familiar with the categories and you want to find out if there is a module that performs a certain task, you might want to get the file 00modlist.long.html, also in the modules directory. That file is the "Perl 5 Modules List." It contains a list of all the modules, by category, with a brief description of the purpose of each module and a link to the author's CPAN directory for downloading.Here is a list of the categories; there are currently 22 categories, plus one for modules that don't fit anywhere else:02_Perl_Core_Modules 03_Development_Support 04_Operating_System_Interfaces 05_Networking_Devices_Inter_Process 06_Data_Type_Utilities 07_Database_Interfaces 08_User_Interfaces 09_Interfaces_to_Other_Languages 10_File_Names_Systems_Locking 11_String_Processing_Language_Text_Process 12_Option_Argument_Parameter_Processing 13_Internationalization_and_Locale 14_Authentication_Security_Encryption 15_World_Wide_Web_HTML_HTTP_CGI 16_Server_and_Daemon_Utilities 17_Archiving_and_Compression 18_Images_Pixmap_Bitmap_Manipulation 19_Mail_and_Usenet_News 20_Control_Flow_Utilities 21_File_Handle_Input_Output 22_Microsoft_Windows_Modules 23_Miscellaneous_Modules 99_Not_In_Modulelist
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Documentation
- Content preview·Buy reprint rights for this chapterPerl documentation is written in a language known as pod (plain old documentation). Pod is a set of simple tags that can be processed to produce documentation in the style of Unix manpages. There are also several utility programs available that process pod text and generate output in different formats. Pod tags can be intermixed with Perl commands, or they can be saved in a separate file, which usually has a .pod extension. The pod tags and the utility programs that are included in the Perl distribution are described in Chapter 4.On Unix, the standard Perl installation procedure generates manpages for the Perl documentation from their pod format, although your system administrator might also choose to install the documentation as HTML files. You can also use this procedure to generate manpages for CPAN modules when you install them. You might need to modify your MANPATH environment variable to include the path to the Perl manpages, but then you should be able to read the documentation with the man command. In addition, Perl comes with its own command, perldoc, which formats the pod documentation and displays it. perldoc is particularly useful for reading module documentation, which might not be installed as manpages; you can also use it for reading the core Perl documentation.The ActiveState Win32 port comes with documentation in HTML format; you can find it in the /docs subdirectory of the distribution. Documentation specific to ActiveState's Perl for Win32 is installed in the /docs/Perl-Win32 subdirectory.The native Win32 port installs the perldoc command for formatting and reading Perl documentation; it also provides an option during installation for the documentation to be formatted and saved as HTML files.Perl comes with lots of online documentation. To make life easier, the manpages have been divided into separate sections so you don't have to wade through hundreds of pages of text to find what you are looking for. You can read them with either theAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 3: The Perl Interpreter
- Content preview·Buy reprint rights for this chapterThe perl executable, normally installed in /usr/bin or /usr/local/bin on your machine, is also called the perl interpreter. Every Perl program must be passed through the Perl interpreter in order to execute. The first line in many Perl programs is something like:
#!/usr/bin/perl
For Unix systems, this#!
(hash-bang or shebang) line tells the shell to look for the /usr/bin/perl program and pass the rest of the file to that program for execution. Sometimes you'll see different pathnames to the Perl executable, such as /usr/local/bin/perl. You might see perl5 instead of perl on sites that still depend on older versions of Perl. Or you'll see command-line options tacked on the end, such as the notorious -w switch, which produces warning messages. But almost all Perl programs on Unix start with some variation of this line.If you get a mysterious "Command not found" error on a Perl program, it's often because the path to the Perl executable is wrong. When you download Perl programs off the Internet, copy them from one machine to another, or copy them out of a book (like this one!), the first thing you should do is make sure that the#!
line points to the location of the Perl interpreter on your system.So what does the Perl interpreter do? It compiles the program internally into a parse tree and then executes it immediately. Perl is commonly known as an interpreted language, but this is not strictly true. Since the interpreter actually does convert the program into byte code before executing it, it is sometimes called an interpreter/compiler, if anything at all. Although the compiled form is not stored as a file, release 5.005 of Perl includes a working version of a standalone Perl compiler.What does all this brouhaha mean for you? When you write a Perl program, you can just give it a correct#!
line at the top of the script, make it executable withchmod +x
, and run it. For 95% of Perl programmers in this world, that's all you'll care about.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Command Processing
- Content preview·Buy reprint rights for this chapterIn addition to specifying a
#!
line, you can also specify a short script directly on the command line. Here are some of the possible ways to run Perl:-
Issue the perl command, writing your script line by line via -e switches on the command line:
perl -e 'print "Hello, world\n"' #Unix perl -e "print \"Hello, world\n\"carview.php?tsp=" #Win32
-
Issue the perl command, passing Perl the name of your script as the first parameter (after any switches):
perl testpgm
-
On Unix systems that support the
#!
notation, specify the Perl command on the#!
line, make your script executable, and invoke it from the shell (as described above). -
Pass your script to Perl via standard input. For example, under Unix:
echo "print 'Hello, world'" | perl -
or (unlessignoreeof
is set):% perl print "Hello, world\n"; ^D
-
On Win32 systems, you can associate an extension (e.g., .plx) with a file type and double-click on the icon for a Perl script with that file type. If you are using the ActiveState version of Win32 Perl, the installation script normally prompts you to create the association.
-
On Win32 systems, if you double-click on the icon for the Perl executable, you'll find yourself in a command-prompt window, with a blinking cursor. You can enter your Perl commands, indicating the end of your input with CTRL-Z, and Perl will compile and execute your script.
Perl parses the input file from the beginning, unless you've specified the -x switch (see Section 3.2 later in this chapter). If there is a#!
line, it is always examined for switches as the line is being parsed. Thus, switches behave consistently regardless of how Perl was invoked.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Command-Line Options
- Content preview·Buy reprint rights for this chapterPerl expects any command-line options, also known as switches or flags, to come first on the command line. The next item is usually the name of the script, followed by any additional arguments (often filenames) to be passed into the script. Some of these additional arguments may be switches, but if so, they must be processed by the script, since Perl gives up parsing switches as soon as it sees either a non-switch item or the special
--
switch that terminates switch processing.A single-character switch with no argument may be combined (bundled) with the switch that follows it, if any. For example:#!/usr/bin/perl -spi.bak
is the same as:#!/usr/bin/perl -s -p -i.bak
Perl recognizes the switches listed in Table 3.1.Table 3.1: Perl Switches Switch Function -- Terminates switch processing, even if the next argument starts with a minus. It has no other effect.-0[octnum] Specifies the record separator ($/
) as an octal number. If octnum is not present, the null character is the separator. Other switches may precede or follow the octal number.-a Turns on autosplit mode when used with -n or -p. An implicitsplit
of the@F
array is inserted as the first command inside the implicitwhile
loop produced by -n or -p. The default field delimiter is whitespace; a different field delimiter may be specified using -F.-c Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Environment Variables
- Content preview·Buy reprint rights for this chapterEnvironment variables are used to set user preferences. Individual Perl modules or programs are always free to define their own environment variables, and there is also a set of special environment variables that are used in the CGI environment (see Chapter 9).Perl uses the following environment variables:
- HOME
-
Used if
chdir
has no argument. - LOGDIR
-
Used if
chdir
has no argument and HOME is not set. - PATH
-
Used in executing subprocesses and in finding the script if -S is used.
- PATHEXT
-
On Win32 systems, if you want to avoid typing the extension every time you execute a Perl script, you can set the PATHEXT environment variable so that it includes Perl scripts. For example:
> set PATHEXT=%PATHEXT%;.PLX
This setting lets you type:> myscript
without including the file extension. Take care when setting PATHEXT permanently—it also includes executable file types like .com, .exe, .bat, and .cmd. If you inadvertently lose those extensions, you'll have difficulty invoking applications and script files. - PERL5LIB
-
A colon-separated list of directories in which to look for Perl library files before looking in the standard library and the current directory. If PERL5LIB is not defined, PERLLIB is used. When running taint checks, neither variable is used. The script should instead say:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The Perl Compiler
- Content preview·Buy reprint rights for this chapterA native-code compiler for Perl is now (as of Perl 5.005) part of the standard Perl distribution. The compiler allows you to distribute Perl programs in binary form, which enables easy packaging of Perl-based programs without having to depend on the source machine having the correct version of Perl and the correct modules installed. After the initial compilation, running a compiled program should be faster to the extent that it doesn't have to be recompiled each time it's run. However, you shouldn't expect that the compiled code itself will run faster than the original Perl source or that the executable will be smaller—in reality, the executable file is likely to be significantly bigger.This initial release of the compiler is still considered to be a beta version. It's distributed as an extension module, B, that comes with the following backends:
- Bytecode
-
Translates a script into platform-independent Perl byte code.
- C
-
Translates a Perl script into C code.
- CC
-
Translates a Perl script into optimized C code.
- Deparse
-
Regenerates Perl source code from a compiled program.
- Lint
-
Extends the Perl -w option. Named after the Unix Lint program-checker.
- Showlex
-
Shows lexical variables used in functions or files.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Threads
- Content preview·Buy reprint rights for this chapterPerl 5.005 also includes the first release of a native multithreading capability, which is distributed with Perl as a set of modules. Since this is an initial release, the threads modules are considered to be beta software and aren't automatically compiled in with Perl. Therefore, the decision to use the threads feature has to be made during installation, so it can be included in the build of Perl. Or you might want to build a separate version of Perl for testing purposes.Chapter 8 describes the individual Thread modules. For information on what threads are and how you might use them, see the article "Threads" in the Summer 1998 issue of The Perl Journal. There is also an explanation of threads in the book Programming with Perl Modules from O'Reilly's Perl Resource Kit, Win32 Edition.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 4: The Perl Language
- Content preview·Buy reprint rights for this chapterThis chapter is a quick and merciless guide to the Perl language itself. If you're trying to learn Perl from scratch, and you'd prefer to be taught rather than to have things thrown at you, then you might be better off with Learning Perl by Randal Schwartz and Tom Christiansen, or Learning Perl on Win32 Systems by Randal Schwartz, Erik Olson, and Tom Christiansen. However, if you already know some other programming languages and just want to hear the particulars of Perl, this chapter is for you. Sit tight, and forgive us for being terse: we have a lot of ground to cover.If you want a more complete discussion of the Perl language and its idiosyncrasies (and we mean complete), see Programming Perl by Larry Wall, Tom Christiansen, and Randal Schwartz.Perl is a particularly forgiving language, as far as program layout goes. There are no rules about indentation, newlines, etc. Most lines end with semicolons, but not everything has to. Most things don't have to be declared, except for a couple of things that do. Here are the bare essentials:
- Whitespace
-
Whitespace is required only between items that would otherwise be confused as a single term. All types of whitespace—spaces, tabs, newlines, etc.—are equivalent in this context. A comment counts as whitespace. Different types of whitespace are distinguishable within quoted strings, formats, and certain line-oriented forms of quoting. For example, in a quoted string, a newline, a space, and a tab are interpreted as unique characters.
- Semicolons
-
Every simple statement must end with a semicolon. Compound statements contain brace-delimited blocks of other statements and do not require terminating semicolons after the ending brace. A final simple statement in a block also does not require a semicolon.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Program Structure
- Content preview·Buy reprint rights for this chapterPerl is a particularly forgiving language, as far as program layout goes. There are no rules about indentation, newlines, etc. Most lines end with semicolons, but not everything has to. Most things don't have to be declared, except for a couple of things that do. Here are the bare essentials:
- Whitespace
-
Whitespace is required only between items that would otherwise be confused as a single term. All types of whitespace—spaces, tabs, newlines, etc.—are equivalent in this context. A comment counts as whitespace. Different types of whitespace are distinguishable within quoted strings, formats, and certain line-oriented forms of quoting. For example, in a quoted string, a newline, a space, and a tab are interpreted as unique characters.
- Semicolons
-
Every simple statement must end with a semicolon. Compound statements contain brace-delimited blocks of other statements and do not require terminating semicolons after the ending brace. A final simple statement in a block also does not require a semicolon.
- Declarations
-
Only subroutines and report formats need to be explicitly declared. All other user-created objects are automatically created with a null or 0 value unless they are defined by some explicit operation such as assignment. The -w command-line switch will warn you about using undefined values.You may force yourself to declare your variables by including the
use strict
pragma in your programs (see Chapter 8, for more information on pragmas andstrict
in particular). This makes it an error to not explicitly declare your variables.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Data Types and Variables
- Content preview·Buy reprint rights for this chapterPerl has three basic data types: scalars, arrays, and hashes.Scalars are essentially simple variables. They are preceded by a dollar sign (
$
). A scalar is either a number, a string, or a reference. (A reference is a scalar that points to another piece of data. References are discussed later in this chapter.) If you provide a string where a number is expected or vice versa, Perl automatically converts the operand using fairly intuitive rules.Arrays are ordered lists of scalars that you access with a numeric subscript (subscripts start at 0). They are preceded by an "at" sign (@
).Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%
).Perl stores numbers internally as either signed integers or double-precision floating-point values. Numeric literals are specified in any of the following floating-point or integer formats:12345 # integer -54321 # negative integer 12345.67 # floating point 6.02E23 # scientific notation 0xffff # hexadecimal 0377 # octal 4_294_967_296 # underline for legibility
Since Perl uses the comma as a list separator, you cannot use a comma for improving legibility of a large number. To improve legibility, Perl allows you to use an underscore character instead. The underscore only works within literal numbers specified in your program, not in strings functioning as numbers or in data read from somewhere else. Similarly, the leading0x
for hex and0
for octal work only for literals. The automatic conversion of a string to a number does not recognize these prefixes—you must do an explicit conversion.Strings are sequences of characters. String literals are usually delimited by either single (Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Statements
- Content preview·Buy reprint rights for this chapterA simple statement is an expression evaluated for its side effects. Every simple statement must end in a semicolon, unless it is the final statement in a block.A sequence of statements that defines a scope is called a block. Generally, a block is delimited by braces, or
{ }
. Compound statements are built out of expressions and blocks. A conditional expression is evaluated to determine whether a statement block will be executed. Compound statements are defined in terms of blocks, not statements, which means that braces are required.Any block can be given a label. Labels are identifiers that follow the variable-naming rules (i.e., they begin with a letter or underscore, and can contain alphanumerics and underscores). They are placed just before the block and are followed by a colon, likeSOMELABEL
here:SOMELABEL: { ...statements... }
By convention, labels are all uppercase, so as not to conflict with reserved words. Labels are used with the loop-control commandsnext
,last
, andredo
to alter the flow of execution in your programs.Theif
andunless
statements execute blocks of code depending on whether a condition is met. These statements take the following forms:if (expression) {block} else {block} unless (expression) {block} else {block} if (expression1) {block} elsif (expression2) {block} ... elsif (lastexpression) {block} else {block}
Section 4.3.1.1: while loops
Thewhile
statement repeatedly executes a block as long as its conditional expression is true. For example:while (<INFILE>) { print OUTFILE, "$_\n"; }
This loop reads each line from the file opened with the filehandle INFILE and prints them to the OUTFILE filehandle. The loop will cease when it encounters an end-of-file.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Special Variables
- Content preview·Buy reprint rights for this chapterSome variables have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator (
$
,@
, or%
), such as$_
. The explicit, long-form names shown are the variables' equivalents when you use the English module by including "use English;
" at the top of your program.The most commonly used special variable is$_
, which contains the default input and pattern-searching string. For example, in the following lines:foreach ('hickory','dickory','doc') { print; }
The first time the loop is executed, "hickory" is printed. The second time around, "dickory" is printed, and the third time, "doc" is printed. That's because in each iteration of the loop, the current string is placed in$_
, and is used by default byprint
. Here are the places where Perl will assume$_
even if you don't specify it:-
Various unary functions, including functions like
ord
andint
, as well as the all file tests (-f
,-d
) except for-t
, which defaults toSTDIN
. -
Various list functions like
print
andunlink
. -
The pattern-matching operations
m//
,s///
, andtr///
when used without an=~
operator. -
The default iterator variable in a
foreach
loop if no other variable is supplied. -
The implicit iterator variable in the
grep
andmap
functions. -
The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a
while
test (i.e., <filehandle>). Note that outside of awhile
test, this will not happen.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Operators
- Content preview·Buy reprint rights for this chapterTable 4.3 lists all the Perl operators from highest to lowest precedence and indicates their associativity.
Table 4.3: Perl Associativity and Operators, Listed by Precedence Associativity Operators Left Terms and list operators (leftward) Left ->
(method call, dereference)Nonassociative ++ --
(autoincrement, autodecrement)Right **
(exponentiation)Right ! ~ \
and unary+
and-
(logical not, bit-not, reference, unary plus, unary minus)Left =~ !~
(matches, doesn't match)Left * / % x
(multiply, divide, modulus, string replicate)Left + - .
(addition, subtraction, string concatenation)Left << >>
(left bit-shift, right bit-shift)Nonassociative Named unary operators and file-test operatorsNonassociative < > <= >= lt gt le ge
(less than, greater than, less than or equal to, greater than or equal to, and their string equivalents.Nonassociative == != <=> eq ne cmp
(equal to, not equal to, signed comparison, and their string equivalents)Left &
(bit-and)Left | ^
(bit-or, bit-xor)Left &&
(logical AND)Left ||
(logical OR)Nonassociative .. …
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Regular Expressions
- Content preview·Buy reprint rights for this chapterRegular expressions are used several ways in Perl. They're used in conditionals to determine whether a string matches a particular pattern. They're also used to find patterns in strings and replace the match with something else.The ordinary pattern match operator looks like
/
pattern/
. It matches against the$_
variable by default. If the pattern is found in the string, the operator returns true ("1"
); if there is no match, a false value ("carview.php?tsp="
) is returned.The substitution operator looks likes/
pattern/
replace/
. This operator searches$_
by default. If it finds the specified pattern, it is replaced with the string in replace. If pattern is not matched, nothing happens.You may specify a variable other than$_
with the=~
binding operator (or the negated!~
binding operator, which returns true if the pattern is not matched). For example:$text =~ /sampo/;
The following list defines Perl's pattern-matching operators. Some of the operators have alternative "quoting" schemes and have a set of modifiers that can be placed directly after the operators to affect the match operation in some way.-
m/
pattern/gimosx
-
Searches a string for a pattern match. Modifiers are:
Modifier Meaning g
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Subroutines
- Content preview·Buy reprint rights for this chapterSubroutines are declared using one of these forms:
sub name {block} sub name (proto) {block}
Prototypes allow you to put constraints on the arguments you provide to your subroutines.You can also create anonymous subroutines at run-time, which will be available for use through a reference:$subref = sub {block};
The ampersand (&
) is the identifier used to call subroutines. Most of the time, however, subroutines can be used in an expression just like built-in functions. To call subroutines directly:name(args); # & is optional with parentheses name args; # Parens optional if predeclared/imported &name; # Passes current @_ to subroutine
To call subroutines indirectly (by name or by reference):&$subref(args); # & is not optional on indirect call &$subref; # Passes current @_ to subroutine
All arguments to a subroutine are passed as a single, flat list of scalars, and return values are returned the same way. Any arrays or hashes passed in these lists will have their values interpolated into the flattened list.Any arguments passed to a subroutine come in as the array@_
.You may use the explicitreturn
statement to return a value and leave the subroutine at any point.If you want to pass more than one array or hash into or out of a function and have them maintain their integrity, then you will want to pass references as arguments. The simplest way to do this is to take your named variables and put a backslash in front of them in the argument list:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - References and Complex Data Structures
- Content preview·Buy reprint rights for this chapterA Perl reference is a fundamental data type that "points" to another piece of data or code. A reference knows the location of the information and what type of data is stored there.A reference is a scalar and can be used anywhere a scalar can be used. Any array element or hash value can contain a reference (a hash key cannot contain a reference), and this is how nested data structures are built in Perl. You can construct lists containing references to other lists, which can contain references to hashes, and so on.You can create a reference to an existing variable or subroutine by prefixing it with a backslash:
$a = "fondue"; @alist = ("pitt", "hanks", "cage", "cruise"); %song = ("mother" => "crying", "brother" => "dying"); sub freaky_friday { s/mother/daughter/ } # Create references $ra = \$a; $ralist = \@alist; $rsong = \%song; $rsub = \&freaky_friday; # '&' required for subroutine names
References to scalar constants are created similarly:$pi = \3.14159; $myname = \"Charlie";
Note that all references are prefixed by a$
, even if they refer to an array or hash. All references are scalars, thus you can copy a reference to another scalar or even reference another reference:$aref = \@names; $bref = $aref; # both refer to @names $cref = \$aref; # $cref is a reference to $aref
Because arrays and hashes are collections of scalars, you can create references to individual elements by prefixing their names with backslashes:$star = \$alist[2]; # refers to third element of @alist $action = \$song{mother}; # refers to the 'mother' value of %song
Section 4.8.1.1: Referencing anonymous data
It is also possible to take references to literal data not stored in a variable. This data is called anonymous because it is not bound to any named variable.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Filehandles
- Content preview·Buy reprint rights for this chapterA filehandle is the name for an I/O connection between your Perl process and the operating system. Filehandle names are like label names, but use their own namespace. Like label names, the convention is to use all uppercase letters for filehandle names.Every Perl program has three filehandles that are automatically opened: STDIN, STDOUT, and STDERR. By default, the
print
andwrite
functions write to STDOUT. Additional filehandles are created using theopen
function:open (DATA, "numbers.txt");
DATA is the new filehandle that is attached to the external file, which is now opened for reading. You can open filehandles for reading, writing, and appending to external files and devices. To open a file for writing, prefix the filename with a greater-than sign:open(OUT, ">outfile");
To open a file for appending, prefix the filename with two greater-than signs:open(LOGFILE, ">>error_log");
Theopen
function returns true if the file is successfully opened, and false if it failed to open. Opening a file can fail for any number of reasons: a file does not exist, is write-protected, or you don't have permission for a file or directory. However, a filehandle that has not been successfully opened can still be read from (giving you an immediate EOF) or written to, with no noticeable effects.You should always check the result ofopen
immediately and report an error if the operation does not succeed. Thewarn
function can report an error to standard error if something goes wrong, anddie
can terminate your program and tell you what went wrong. For example:open(LOGFILE, "/usr/httpd/error_log") || warn "Could not open /usr/httpd/error_log.\n"; open(DATA, ">/tmp/data") || die "Could not create /tmp/data\n.";
Once the file is opened, you can access the data using the diamond operator,<
filehandle>. This is the line-input operator. When used on a filehandle in a scalar context, it will return a line from a filehandle as a string. Each time it is called it will return the next line from the filehandle, until it reaches the end-of-file. The operator keeps track of which line it is on in the file, unless the filehandle is closed and reopened, resetting the operator to the top-of-file.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Formats
- Content preview·Buy reprint rights for this chapterFormats are a mechanism for generating formatted reports for outputting data. Formats are defined with the
format
keyword. The general form looks like:format name = ...template lines... ...argument line... .
Most of your format names will be the same as the filehandle names for which they are used. The default format for a filehandle is the one with the same name.The format definition is like a subroutine definition. It doesn't contain immediately executed code and can therefore be placed anywhere in the file with the rest of the program; they are commonly placed near the end of the file with subroutine definitions. To output to a format, use thewrite
function instead ofprint
.The template lines contain literal text and fieldholders. Fieldholders contain symbols that describe the size and positioning of the area on the line where data is output. An argument line immediately follows a template line that contains the fields to be replaced by data. The argument line is a list of variables (or expressions), separated by commas, which fill the fields in the previous line in the order they are listed.Here's an example of a template line with two fieldholders, and the argument line that follows:Hello, my name is @<<<<<<<<<< and I'm @<< years old. $name, $age
The fieldholders are the@<<<<<<<<<<
and@<<
, which specify left-justified text fields with 11 and 3 characters, respectively.Most fieldholders start with@
. The characters following the@
indicate the type of field, while the number of characters (including the@
) indicate the field width. The following fieldholder characters determine the positioning of text fields:-
<<<<
(left angle-brackets) -
A left-justified field; if the value is shorter than the field width, it will be padded on the right with spaces.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Pod
- Content preview·Buy reprint rights for this chapterPod is a simple, but surprisingly capable, text formatter that uses tags to tell a translator how to format the text. The tags serve several purposes:
-
They tell the formatter how to lay out text on the page.
-
They provide font and cross-reference information.
-
They start and stop parsing of code.
The last item is indicative of one of pod's most useful features;—that it can be intermixed with Perl code. While it can be difficult to force yourself to go back and write documentation for your code after the fact, with Perl you can simply intermingle the documentation with the code, and do it all at once. It also lets you use the same text as both code documentation and user documentation if you wish.A pod translator reads a file paragraph by paragraph, ignoring text that isn't pod, and converting it to the proper format. Paragraphs are separated from each other by blank lines (not just by a newline). The various translators recognize three kinds of paragraphs:- Command
-
Commands begin with
=
, followed immediately by the command identifier:=cut
They can also be followed by text:=head2 Second-level head
A blank line signals the end of the command. - Text
-
A paragraph consisting of a block of text, generally filled and possibly justified, depending on the translator. For example, a command like
=head2
is probably going to be followed with a text paragraph:=head2 Pod Pod is a simple, but surprisingly capable, text formatter that uses tags to tell a translator how to format the text.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Chapter 5: Function Reference
- Content preview·Buy reprint rights for this chapterThis chapter gives a brief description of Perl's built-in functions. Each description gives the syntax of the function, with the types and order of its arguments.Required arguments are shown in italics, separated by commas. If an argument must be a specific variable type, that variable's identifier will be used (i.e., a percent sign for a hash,
%
hash). Optional arguments are placed in brackets. Do not actually use the brackets in your function calls unless you really want to use an anonymous hash reference.There are different ways to use a built-in function. For starters, any argument that requires a scalar value can be made up of any expression that returns one. For example, you can obtain the square root of the first value in an array:$root = sqrt (shift @numbers);
shift
removes the first element of@numbers
and returns it to be used bysqrt
.Many functions take a list of scalars for arguments. Any array variable or other expression that returns a list can be used for all or part of the arguments. For example:chmod (split /,/ FILELIST>); # an expression returns a list chmod 0755, @executables; # array used for part of arguments
In the first line, thesplit
expression reads a string from a filehandle and splits it into a list. The list provides proper arguments forchmod
. The second line uses an array that contains a list of filenames forchmod
to act upon.Parentheses are not required around a function's arguments. However, without parentheses, functions are viewed as operators in an expression (the same is true of predeclared subroutines). If you use a function in a complex expression, you may want to use parentheses for clarity. See Chapter 4, for more about precedence in Perl expressions.Here are Perl's functions and function-like keywords, arranged by category. Note that some functions appear under more than one heading.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Perl Functions by Category
- Content preview·Buy reprint rights for this chapterHere are Perl's functions and function-like keywords, arranged by category. Note that some functions appear under more than one heading.
- Scalar manipulation
-
chomp
,chop
,chr
,crypt
,hex
,index
,lc
,lcfirst
,length
,oct
,ord
,pack
,q//
,qq//
,reverse
,rindex
,sprintf
,substr
,tr///
,uc
,ucfirst
,y///
- Regular expressions and pattern matching
-
m//
,pos
,qr//
,quotemeta
,s///
,split
,study
- Numeric functions
-
abs
,atan2
,cos
,exp
,hex
,int
,log
,oct
,rand
,sin
,sqrt
,srand
- Array processing
-
pop
,push
,shift
,splice
,unshift
- List processing
-
grep
,join
,map
,qw//
,reverse
,sort
,unpack
- Hash processing
-
delete
,each
,exists
,keys
,values
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Perl Functions in Alphabetical Order
- Content preview·Buy reprint rights for this chapterabsabs valueDescriptionReturns the absolute value of its argument (or
$_
if omitted).acceptaccept newsocket, genericsocketDescriptionReadies a server process to accept socket connections from clients. Execution is suspended until a connection is made, at which time the newsocket filehandle is opened and attached to the newly made connection. The function returns the connected address if the call succeeds, or returns false otherwise (and it puts the error code into$!
). genericsocket must be a filehandle already opened via thesocket
function and bound to one of the server's network addresses.alarmalarm nDescriptionSends aSIGALRM
signal to the executing Perl program after n seconds. On some older systems, alarms go off "at the top of the second," so, for instance, analarm 1
may go off anywhere between 0 to 1 seconds from now, depending on when in the current second it is. Analarm 2
may go off anywhere from 1 to 2 seconds from now. And so on.Each call disables the previous timer, and an argument of0
may be supplied to cancel the previous timer without starting a new one. The return value is the number of seconds remaining on the previous timer.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 6: Debugging
- Content preview·Buy reprint rights for this chapterOf course everyone writes perfect code on the first try, but on those rare occasions when something goes wrong and you're having trouble with your Perl script, there are several things you can try:
-
Run the script with the -w switch, which prints warnings about possible problems in your code.
-
Use the Perl debugger.
-
Use another debugger, or a profiler such as the Devel::DProf module.
The major focus of this chapter is the Perl debugger, which provides an interactive Perl environment. The chapter also describes the use of the DProf module and the dprofpp program that comes with it; together they can provide you with a profile of your Perl script. If you've ever used any debugger, and you understand concepts such as breakpoints and backtraces, you'll have no trouble learning to use the Perl debugger. Even if you haven't used another debugger, the command descriptions and some experimenting should get you going.To run your script under the Perl source debugger, invoke Perl with the -d switch:perl -d myprogram
This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. If your program takes any switches or arguments, you must include them in the command:perl -d myprogram myinput
In Perl, the debugger is not a separate program as it is in the typical compiled environment. Instead, the -d flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. That means your code must first compile correctly for the debugger to work on it—the debugger won't run until you have fixed all compiler errors.After your code has compiled, and the debugger has started up, the program halts right before the first runtime executable statement (but see Section 6.3 below regarding compile time statements) and waits for you to enter a debugger command. Whenever the debugger halts and shows you a line of code, it always displays the line it's about to execute, rather than the one it has just executed.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Perl Debugger
- Content preview·Buy reprint rights for this chapterTo run your script under the Perl source debugger, invoke Perl with the -d switch:
perl -d myprogram
This works like an interactive Perl environment, prompting for debugger commands that let you examine source code, set breakpoints, get stack backtraces, change the values of variables, etc. If your program takes any switches or arguments, you must include them in the command:perl -d myprogram myinput
In Perl, the debugger is not a separate program as it is in the typical compiled environment. Instead, the -d flag tells the compiler to insert source information into the parse trees it's about to hand off to the interpreter. That means your code must first compile correctly for the debugger to work on it—the debugger won't run until you have fixed all compiler errors.After your code has compiled, and the debugger has started up, the program halts right before the first runtime executable statement (but see Section 6.3 below regarding compile time statements) and waits for you to enter a debugger command. Whenever the debugger halts and shows you a line of code, it always displays the line it's about to execute, rather than the one it has just executed.Any command not recognized by the debugger is directly executed as Perl code in the current package. In order to be recognized by the debugger, the command must start at the beginning of the line, otherwise the debugger assumes it's for Perl.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Debugger Commands
- Content preview·Buy reprint rights for this chapterThe debugger understands the following commands:aa [line] commandDescriptionSets an action to be done before the line is executed. The following steps are taken:
-
Checks for a breakpoint at this line.
-
Prints the line if necessary.
-
Performs any actions associated with the line.
-
Prompts the user if at a breakpoint or in single-step mode.
-
Evaluates the line.
For example, the following prints the value of$foo
(and "DB FOUND
") every time line 53 is passed:a 53 print "DB FOUND $foo\n"
AADescriptionDeletes all installed actions.bb [line] [condition]DescriptionSets a breakpoint at line, which must begin an executable statement. If line is omitted, sets a breakpoint on the line that is about to be executed. condition, if given, is evaluated each time the statement is reached, and a breakpoint is taken if condition is true:b 237 $x > 30 b 33 /pattern/i
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Using the Debugger
- Content preview·Buy reprint rights for this chapterIf you have any compile time executable statements (code within a
BEGIN
block or ause
statement), they are not stopped by the debugger, althoughrequire
s are.The debugger prompt is something like this:DB<8>
or even this:DB<<17>>
where the number in angle brackets is the command number. A csh-like history mechanism lets you access previous commands by number. For example,!17
repeats command number 17. The number of angle brackets indicates the depth of the debugger. You get more than one set of brackets, for example, if you're already at a breakpoint and then you print out the result of a function call that itself also has a breakpoint.If you want to enter a multiline command, such as a subroutine definition with several statements, you can use a backslash to escape the newline that would normally end the debugger command:DB<1> sub foo { \ cont: print "fooline\n"; \ cont: } DB<2> foo fooline
You can maintain limited control over the Perl debugger from within your Perl script. You might do this, for example, to set an automatic breakpoint at a certain subroutine whenever a particular program is run under the debugger. Setting$DB::single
to1
causes execution to stop at the next statement, as though you'd used the debugger'ss
command. Setting$DB::single
to2
is equivalent to typing then
command, and the$DB::trace
variable can be set to1
to simulate thet
command.Once you are in the debugger, you can terminate the session by enteringq
or CTRL-D at the prompt. You can also restart the debugger withR
.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Customizing the Debugger
- Content preview·Buy reprint rights for this chapterYou can do some customizing by setting up a .perldb file with initialization code. When it starts up, the debugger reads and processes this file. For instance, you can set up aliases like these:
$DB::alias{'len'} = 's/^len(.*)/p length($1)/'; $DB::alias{'stop'} = 's/^stop (at|in)/b/'; $DB::alias{'ps'} = 's/^ps\b/p scalar /'; $DB::alias{'quit'} = 's/^quit\b.*/exit/';
You can also use this file to set options and to define a subroutine,&afterinit
, to be executed after the debugger is initialized.After the configuration file has been processed, the debugger consults the environment variable PERLDB_OPTS and parses its contents as arguments to theO
opt=val
debugger command.While any options can be set in PERLDB_OPTS, the following options can only be specified at startup. If you want to set them in your configuration file, call&parse_options("opt=val")
.-
TTY
-
The TTY to use for debugging I/O.
-
noTTY
-
If set, goes in NonStop mode. On an interrupt, if TTY is not set, it uses the value of
noTTY
or /tmp/perldbtty$$ to find the TTY using Term::Rendezvous. The current variant is to have the name of the TTY in this file. -
ReadLine
-
If false, a dummy
ReadLine
is used so that you can debug ReadLine applications. -
NonStop
-
If true, no interaction is performed until an interrupt.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Perl Profiler
- Content preview·Buy reprint rights for this chapterYou can supply an alternative debugger for Perl to run, by invoking your script with the -d: module switch. One of the most popular alternative debuggers for Perl is DProf, the Perl profiler. As of this writing, DProf was not included with the standard Perl distribution, but it is expected to be included soon.Meanwhile, you can fetch the Devel::DProf module from CPAN. Once it has been properly installed on your system, you can use it to profile the Perl program in testpgm by typing:
perl -d:DProf testpgm
As your script runs, DProf gathers profile information. When the script terminates, the profiler dumps the gathered information to a file called tmon.out. A tool such as dprofpp, which is supplied with the Devel::DProf package, can be run to interpret the profile. If you run dprofpp against the tmon.out file created by DProf in the example above, you'll see something like the following:% dprofpp tmon.out Total Elapsed Time = 0.15 Seconds User+System Time = 0.1 Seconds Exclusive Times %Time Seconds #Calls sec/call Name 30.0 0.030 1 0.0300 Text::Wrap::CODE(0x175f08) 20.0 0.020 1 0.0200 main::CODE(0xc7880) 20.0 0.020 1 0.0200 main::CODE(0xfe480) 10.0 0.010 1 0.0100 Text::Wrap::CODE(0x17151c) 10.0 0.010 10 0.0010 Text::Tabs::expand 0.00 0.000 1 0.0000 lib::CODE(0xfe5b8) 0.00 0.000 3 0.0000 Exporter::export 0.00 0.000 1 0.0000 Config::FETCH 0.00 0.000 1 0.0000 lib::import 0.00 0.000 1 0.0000 Text::Wrap::CODE(0x171438) 0.00 0.000 3 0.0000 vars::import 0.00 0.000 3 0.0000 Exporter::import 0.00 0.000 2 0.0000 strict::import 0.00 0.000 1 0.0000 Text::Wrap::CODE(0x171684) 0.00 0.000 1 0.0000 lib::CODE(0xfe4d4)
The output shows the fifteen subroutines that use the most time—you can then focus your efforts on those subroutines where tuning the code will have the greatest effect. This output is an example of running theAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The perlbug Program
- Content preview·Buy reprint rights for this chapterAs you develop and debug your own code, it's possible that you'll run into a bug in Perl itself—if you do, the best way to report it is with the perlbug program. perlbug is a Perl program designed to automate the process of reporting bugs in the Perl standard distribution and the standard modules. It works interactively, prompting you for the information needed and generating an email message addressed to perlbug@perl.com. (If the bug you found is in one of the non-standard Perl ports, see the documentation for that port to find out how to report bugs.) When you run perlbug, it prompts you to include all relevant information, making it easier for the Perl developers to reproduce and track down the bug. If you come up with a patch to resolve the problem, include that too.Don't use perlbug as a way to get help debugging your code (see the list of newsgroups and other resources in Chapter 1, for that), but if you believe you've found a bug in Perl itself, perlbug is the way to report it.To run perlbug, simply enter the command, with any options you want to include. For example:
% perlbug -t
The possible options are:- -a address
-
Email address to send report to. Default is perlbug@perl.com.
- -b body
-
Body of report. If not included on the command line or in a file, you are given a chance to edit it.
- -C
-
Don't send a copy to your Perl administrator.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 7: Packages, Modules, and Objects
- Content preview·Buy reprint rights for this chapterOver the years, Perl has evolved from a utilitarian scripting tool into a sophisticated object-oriented programming language. Many people continue to use Perl just for simple scripts, and Perl will continue to make simple tasks easy. However, Perl can also make difficult tasks possible, by writing reusable code and using object-oriented programming techniques.This chapter explains what Perl modules are and how to use them in your programs. Modules are written to accomplish tasks that either aren't implemented by Perl's built-in functions, or that could be done better. We say modules are "reusable" because anyone who needs to accomplish the same task can use that module instead of writing the code from scratch. As you write more and more Perl code, you'll undoubtedly find yourself using many of the modules other Perl programmers have provided. You may also find yourself writing modules and making them available for others to use.The remainder of this book describes a significant portion of the functionality that's present in publicly available Perl modules. You'll find that a number of standard or core modules are distributed with Perl; many of these modules are discussed in Chapter 8. Scores of other modules are available on CPAN, and virtually any task you'd like to accomplish in Perl is implemented in a module found there. For unbundled modules, you'll need to install the module on your system, and then integrate it into your program with the
use
function.Theuse
function is often the key to working with modules. For example, to bring the functionality of the popular CGI module into your program, you need to install the CGI.pm module (the .pm stands for Perl module) and put this line near the top of your program:use CGI;
Now your program can make use of the many functions and variables made available by the CGI module.Packages (from which modules are built) are also the mechanism by which Perl's object-oriented features are implemented. But object-oriented programming isn't for everyone, and there's nothing in packages that forces the programmer to work with the object-oriented paradigm.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Namespaces and Packages
- Content preview·Buy reprint rights for this chapterA namespace does what it says: it stores names (or identifiers), including names of variables, subroutines, filehandles, and formats. Each namespace has its own symbol table, which is basically a hash with a key for each identifier.The default namespace for programs is
main
, but you may define other namespaces and variables and use them in your program. Variables in different namespaces can even have the same name, but they are completely distinct from one another.In Perl, a namespace is held in a package. By convention, package names start with a capital letter, and you should follow that convention when you create your own packages.Each package starts with apackage
declaration. Thepackage
call takes one argument, the name of the package. Within the scope of a package declaration, all regular identifiers are created within that package (except formy
variables).From inside one package, you can refer to variables from another package by "qualifying" them with the package name. To do this, place the name of the package followed by two colons (::
) before the identifier's name, i.e.,$Package::varname
.If the package name is null, themain
package is assumed. For example,$var
and$::var
are the same as$main::var
.Packages may be nested inside other packages. However, the package name must still be fully qualified. For example, if the packageProvince
is declared inside the packageNation
, a variable in the Province package is called as$Nation::Province::var
. You cannot use a "relative" package name such as$Province::var
within theNation
package for the same thing.The defaultmain
namespace contains all other packages within it.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Modules
- Content preview·Buy reprint rights for this chapterA module is a package defined in a file whose name is the same as the package. Perl locates modules by searching the
@INC
array, which contains a list of library directories. Perl's use of@INC
is roughly comparable to the Unix shell's use of the PATH environment variable to locate executable programs.@INC
is defined when Perl is built, and can be supplemented with the -I command-line option to Perl or withuse lib
within a program.When you refer to ModuleName in your program, Perl searches in the directories listed in@INC
for the module file ModuleName.pm, and uses the first one it finds. When you refer to a module embedded in another package, such asParentPackage::ModuleName
, Perl looks for a ParentPackage/ subdirectory in the@INC
path, and for a ModuleName.pm file in that subdirectory.Every Perl installation includes a central lib directory. The actual pathname of this directory varies from system to system, but it's commonly /usr/lib/perl or /usr/local/lib/perl. Looking at the central lib directory for your Perl distribution, you'll see something like this:% ls -aF /usr/local/lib/perl ./ I18N/ bigfloat.pl less.pm ../ IO/ bigint.pl lib.pm AnyDBM_File.pm IPC/ bigrat.pl locale.pm AutoLoader.pm Math/ blib.pm look.pl AutoSplit.pm Net/ cacheout.pl man/ Benchmark.pm Pod/ chat2.pl newgetopt.pl Bundle/ Search/ complete.pl open2.pl CGI/ SelectSaver.pm constant.pm open3.pl CGI.pm SelfLoader.pm ctime.pl perl5db.pl CPAN/ Shell.pm diagnostics.pm pod/ CPAN.pm Symbol.pm dotsh.pl pwd.pl Carp.pm Sys/ dumpvar.pl shellwords.pl ...
When you request theAnyDBM_File
module, it uses AnyDBM_File.pm. When you request theMath::Complex
module, it looks for Math/Complex.pm.A module can be included in your program withAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Object-Oriented Perl
- Content preview·Buy reprint rights for this chapterIn Perl circles, modules and object-oriented programming are often spoken of in the same breath. But just because the programmer has written a package and a subroutine doesn't mean that the code is objectified.A module that describes a class must contain a special subroutine to create an object. (Each object that is created is an instance of a class.) This subroutine is called a constructor. (Often the constructor is named
new
, butCreate
is also used in Win32 classes.) The constructor creates a new object and returns a reference to it. This reference is a regular scalar variable, except that it refers to some underlying object that knows what class it belongs to. In your programs, you will use the reference to manipulate the object.Methods are subroutines that expect an object reference as a first argument, such as:sub in_class { my $class = shift; # object reference my ($this, $that) = @_; # params }
Methods may be invoked like this:PackageName->constructor(args)->method_name(args);
or:$object = PackageName->constructor(args); $object->method_name(args);
Objects have a specific set of available methods within their class, but they also inherit methods from their parent class, if they have one.Objects are destroyed when the last reference to them goes away. You can control this capture before the object is destroyed with theDESTROY
method. TheDESTROY
method should be defined somewhere in the class. You do not callDESTROY
explicitly; it will be called at an appropriate time. Object references contained in the current object will be freed when the current object is freed. Most of the time you won't need to explicitly destroy an object, but there are occasions where you should, such as when you are done with a socket object.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Object Syntax
- Content preview·Buy reprint rights for this chapterPerl uses two forms of syntax for invoking methods on objects. For both types of syntax, the object reference or class name is given as the first argument. A method that takes a class name is called a class method, and one that takes an object reference is called an instance method.Class methods provide functionality for the entire class, not just for a single object that belongs to the class. Class methods expect a class name as their first argument. Following this explanation, a constructor is an example of a class method:
sub new { my $self = {}; bless $self; return $self; }
On the other hand, an instance method expects an object reference as its first argument. An instance method will shift the first argument and use this argument as a reference:sub instance_method { my $self = shift; my($one, $two, $three) = @_; # do stuff }
Here is an example of a constructor creating a new object and returning a reference:$tri = new Triangle::Right (side1 => 3, side2 => 4);
This example creates a new right-triangle object and references it with$tri
. The parameters are given as a hash-style list. This is common for constructors, as they set initial parameters for an object that is probably just a hash. Now that we have an object, we can invoke some method on it. Suppose Triangle::Right defines a method,hypot
, that returns the length of the hypotenuse for a given right-triangle object. It would be used like this:$h = hypot $tri; print "The hypotenuse is: $h.\n";
In this particular example, there happens to be no additional arguments to thehypot
method, but there could have been.With the arrow (->
) notation, the left side of the arrow must be an object reference or a class name, while the right side of the arrow must be a method defined for that object. Any arguments must follow the method inside of parentheses. For example:$obj->method(
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 8: Standard Modules
- Content preview·Buy reprint rights for this chapterWe've talked about the extent to which Perl benefits from user contributions. In fact, many contributed modules are so generally useful that they are now distributed with Perl itself. This chapter describes these "standard modules"-if you are running Perl 5.005, all these modules are already available to you. If you are running an earlier version of Perl, and you find that a module you want isn't on your system, or if you simply don't find what you need among the modules in this chapter, check CPAN for one that does what you want.While this chapter primarily covers standard Perl modules called at execution time from your program, it also covers the "pragmatic" modules that affect the compilation phase. (A pragma is a compiler directive that provides hints to the compiler.) By convention, the names of the pragmatic modules are all lowercase, while the names of other modules begin with an uppercase letter and are of mixed case.The Win32-specific modules are not included in this chapter, but are described in Chapter 19.The following table provides a quick look at the standard modules and what they do:
Module Function AnyDBM_File Provides framework for multiple DBMsattrs Sets or gets attributes of a subroutineAutoLoader Loads functions only on demandAutoSplit Splits a module for autoloadingautouse Postpones load of modules until a function is usedB Perl compiler and toolsbase Establishes IS-A relationship with base class at compile timeBenchmark Checks and compares running times of codeblib Uses MakeMaker's uninstalled version of a packageAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - AnyDBM_File
- Content preview·Buy reprint rights for this chapterProvides a single DBM (Database Manager) interface regardless of the DBM implementation you use. The module inherits from the various DBM packages; by default, it inherits from NDBM_File. If it doesn't find NDBM_File, the default search order is: DB_File, GDBM_File, SDBM_File (which comes with Perl), and finally ODBM_File. You can override this default order by redefining
@ISA
:@AnyDBM_File::ISA = qw(DB_File GDBM_File NDBM_File);
However, an explicituse
takes priority over the@ISA
ordering.Perl'sdbmopen
function actually just callstie
to bind a hash to AnyDBM_File. The effect is to bind the hash to one of the specific DBM classes that AnyDBM_File inherits from.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - attrs
- Content preview·Buy reprint rights for this chapterSets or gets the attributes of subroutines. Attributes are set for a subroutine at compile time; therefore, setting an invalid attribute results in a compile-time error. During execution, when you call
attrs::get
on a subroutine reference or name, it returns the list of attributes that are set. Note thatattrs::get
is not exported. For example:sub test { use attrs qw(locked method); ... } @a = attrs::get(\foo);
The valid attributes are:-
locked
-
Meaningful only when the subroutine or method is to be called by multiple threads. When set on a subroutine that also has the method attribute set, invoking that subroutine implicitly locks its first argument before execution. On a non-method subroutine, a lock is taken on the subroutine itself before execution. The lock semantics are identical to one taken explicitly with the
lock
operator immediately after entering the subroutine. -
method
-
The invoking subroutine is a method.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- AutoLoader
- Content preview·Buy reprint rights for this chapterDelays the loading of functions until they are used. Each function is placed in a file that has the same name as the function, with an .al extension. The files are stored in a subdirectory of the auto/ directory that is named after the package. For example, the function
GoodStuff::whatever
is loaded from the file auto/GoodStuff/whatever.al. Should always beuse
d and notrequire
d.A module using the AutoLoader has the special marker__END__
prior to the declarations for the subroutine to be autoloaded. Any code before this marker is loaded and compiled when the module is used, but at the marker, Perl stops parsing the file.Later, during execution, when a subroutine that isn't yet in memory is called, theAUTOLOAD
function attempts to find it in a directory relative to the location of the module file. For example, if POSIX.pm is in the directory /usr/local/lib/perl5, then the AutoLoader looks for POSIX subroutines in /usr/local/lib/perl5/auto/POSIX/*.al.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - AutoSplit
- Content preview·Buy reprint rights for this chapterSplits a program or module into files that the AutoLoader can handle. It can be called from a program or from the command line:
# from a program use AutoSplit; autosplit_modules(@ARGV) # from the command line perl -MAutoSplit -e 'autosplit(FILE, DIR, KEEP, CHECK, MODTIME)' ... # another interface perl -MAutoSplit -e 'autosplit_lib_modules(@ARGV)' ...
AutoSplit is used by MakeMaker as well as the standard Perl libraries. It operates on a file, splitting off subroutines that come after the__END__
marker and storing them as described above for AutoLoader, creating any necessary directories along the way. AutoSplit has two functions:autosplitautosplit (file, dir, keep, check, modtime)DescriptionSplits the module into files. Each file is given the name of the subroutine it contains, with .al appended.autosplit
also creates the file autosplit.ix, which serves as both a forward declaration of all package routines and as a timestamp showing when the hierarchy was last updated. Takes the following arguments:- file
-
Filename of program or module to be split.
- dir
-
Name of directory hierarchy in which to store the split files.
- keep
-
If false, pre-existing .al files in the auto directory that are no longer part of the module are deleted.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - autouse
- Content preview·Buy reprint rights for this chapterPragma for postponing the loading of a module from compile time to execution time. The module isn't loaded until one of its subroutines is used; the subroutines all have to be exported by the module.
use autouse module => qw(sub1 [sub2 ...])
Use with care, since problems that might otherwise be found during compilation won't crop up until your program is already executing.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B
- Content preview·Buy reprint rights for this chapterThe Perl compiler. To use the compiler, you don't need to use this module. See the O module, which is the user frontend to the compiler; also see the compiler section of Chapter 3. The B module provides the classes for implementing backends for the compiler. If you plan to write a new backend, read the B manpage for the details of the module.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Asmdata
- Content preview·Buy reprint rights for this chapterContains autogenerated data about Perl ops; used to generate bytecode. Any changes made to this file will be lost.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Assembler
- Content preview·Buy reprint rights for this chapterAssembles Perl bytecode.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Bblock
- Content preview·Buy reprint rights for this chapterWalks the basic blocks of a program. Invoked as:
perl -MO=Bblock[,options] filename
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Bytecode
- Content preview·Buy reprint rights for this chapterThe bytecode backend for the Perl compiler. Takes Perl source code and generates platform-independent bytecode that can be run with the byteperl executable or can be loaded via the
byteload_fh
function in the B module. Compiling with the Bytecode backend won't speed up execution of your program, but it may improve start-up time. Invoke as:perl -MO=Bytecode[,options] program
where program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- --
-
Forces end of options.
- -Dopts
-
Debug options, which can be either concatenated or specified separately. Possible options are:
- -fopt
-
Forces individual optimizations on or off. Preceding an optimization with
no-
turns that option off (e.g.,no-compress-nullops
). Possible values of opt are: - -m
-
Compiles as a module rather than as a standalone program.
- -ofilename
-
Sends output to filename instead of STDOUT.
- -O[n]
-
Sets the optimization level to n, where n is an integer. n defaults to 1.
-O1
sets-fcompress-nullops -fomit-sequence-numbers
, and-O6
adds-fstrip-syntax-tree
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::C
- Content preview·Buy reprint rights for this chapterThe C backend for the Perl compiler. Generates C source code from Perl source; the generated code corresponds to Perl's internal structures for running the program. Compiling with the C backend won't speed up execution of your program, but it may improve start-up time. Invoke as:
perl -MO=C[,options] program
where program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- --
-
Forces end of options.
- -Dopts
-
Debug options, which can be either concatenated or specified separately. Possible options are:
- -fopt
-
Forces individual optimizations on or off. Possible values of opt are:
- -ofilename
-
Sends output to filename instead of to STDOUT.
- -O[n]
-
Sets optimization level, where n is an integer. n defaults to 1. Currently, values of 1 and higher set
cog
. - -uPackname
-
Forces apparently unused subroutines from package Packname to be compiled, letting programs use
eval
"foo()"
even if subroutinefoo
isn't seen to be used at compile time. You can specify multiple -u options.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::CC
- Content preview·Buy reprint rights for this chapterThe CC backend for the Perl compiler. Generates optimized C source code that corresponds to your program's flow. The initial version included in Perl 5.005 actually includes few optimizations, but this will change. Programs compiled with this backend may both start up and execute slightly faster. Invoke as:
perl -MO=C[,options] program
where program is the name of the Perl script to compile. Any non-option arguments are treated as the names of objects to be saved; the main program is assumed if there are no extra arguments. Possible options are:- --
-
Forces end of options.
- -Dopts
-
Debug options, which can be either concatenated or specified separately. Possible options are:
- -fopt
-
Forces individual optimizations on or off. Possible values of opt are:
- -mModulename
-
Generates source for an XSUB module instead of for an executable.
- -ofilename
-
Sends output to filename instead of to STDOUT.
- -O[n]
-
Sets optimization level, where n is an integer. n defaults to 1. Currently,
-O1
sets-ffreetmps-each-bblock
, and-O2
sets-ffreetmps-each-loop
. - -uPackname
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Debug
- Content preview·Buy reprint rights for this chapterWalks the Perl syntax tree, printing debug information about ops. Invoke as:
perl -MO=Debug[,exec] filename
Ifexec
is specified, walks in execution order rather than in syntax order.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Deparse
- Content preview·Buy reprint rights for this chapterPerl compiler backend that generates Perl source code from the internal compiled structure of a program. The output won't be exactly the same as the original program, but it will be close. Invoke as:
perl -MO=Deparse[,options] program
program is the name of the program to be deparsed. The options are comma-separated and follow normal backend option conventions. The possible options are:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Disassembler
- Content preview·Buy reprint rights for this chapterDisassembles Perl bytecode.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Lint
- Content preview·Buy reprint rights for this chapterProvides program checking for Perl programs, equivalent to running Perl with the -w option. Named after the Unix lint program for checking C programs. Invoked as:
perl -MO=Lint[,options] program
program is the name of the Perl program to be checked. The options are separated by commas and follow normal backend option conventions. Most of the options are lint-check options, where each option is a word specifying one lint check. Preceding an option withno-
turns off that option. Options specified later override earlier options. There is also one non-lint-check option, -u. Here is the list of available options:- all
-
Turns all warnings on.
- context
-
Warns whenever an array is used in implicit scalar context.
- dollar-underscore
-
Warns whenever
$_
is explicitly used anywhere or whenever it is used as the implicit argument of aprint
statement. - implicit-read
-
Warns whenever an operation implicitly reads a Perl special variable.
- implicit-write
-
Warns whenever an operation implicitly writes to a Perl special variable.
- none
-
Turns off all warnings.
- private-names
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Showlex
- Content preview·Buy reprint rights for this chapterShows lexical variables used in functions or files. Invoke as:
perl -MO=Showlex[,sub] filename
If sub is provided and is the name of a subroutine in file filename, B::Showlex prints the lexical variables used in that subroutine. Otherwise, it prints the file-scope lexicals in filename.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Stackobj
- Content preview·Buy reprint rights for this chapterServes as a helper module for the CC backend.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Terse
- Content preview·Buy reprint rights for this chapterWalks the Perl syntax tree, printing terse information about the ops. Invoke as:
perl -MO=Terse[,exec] filename
Ifexec
is specified, walks the tree in execution order instead of syntax order.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - B::Xref
- Content preview·Buy reprint rights for this chapterPerl compiler backend that generates a cross-reference listing of variables, subroutines, and formats in a Perl program. Results are grouped by file, then subroutine, then package, then objects within the package with line numbers. The line numbers are given as a comma-separated list. A line number may be preceded by one of the following code letters:
Code Meaning %
Subroutine or method call f
Format definition i
Introduction, e.g., a lexical defined with my
s
Subroutine definition Invoke B::Xref like this:perl -MO=Xref[,options] program
program is the Perl program whose cross-reference you want. Options are separated by commas and follow normal backend option conventions. The possible options are:- -D
-
Specifies internal debug options. Most useful if specified with -r option. Debug options are:
- -ofilename
-
Sends output to filename instead of STDOUT.
- -r
-
Produces raw output in machine-readable form for each definition or use of a variable, subroutine, or format.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - base
- Content preview·Buy reprint rights for this chapterProvides a shortcut for setting up
@ISA
. You can say:use base qw(A B);
instead of:BEGIN { require Foo; require Bar; push @ISA, qw(Foo Bar); }
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Benchmark
- Content preview·Buy reprint rights for this chapterProvides routines for timing the execution of your code and formatting the results. Inherits only from the Exporter class. Its functions are:newnew BenchmarkDescriptionReturns the current time. By getting the current time before and after running the code, you can calculate the time it takes the code to run.clearallcacheclearallcacheDescriptionClears the entire cache. Exported on request.clearcacheclearcache (count)DescriptionClears the cached time for count rounds of the null loop. Exported on request.debugBenchmark->debug(flag)DescriptionEnables or disables debugging by setting the
$Benchmark::Debug
flag.disablecachedisablecacheDescriptionDisables use of the cache. Exported on request.enablecacheenablecacheAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - blib
- Content preview·Buy reprint rights for this chapterPragma for testing programs against a package before the package has been installed. Given a directory path,
blib
starts in that directory to look for ablib
directory structure; if it doesn't find one there, it works its way back up five levels. If no path is specified, it starts looking in the current directory.blib
is meant to be used from the command line:perl -Mblib script [args...] perl -Mblib=dir script [args...]
However, you can also call it from a Perl program:use blib; use blib 'dir';
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Carp
- Content preview·Buy reprint rights for this chapterProvides routines for generating error messages. Its subroutines generally report errors from the perspective of the calling program. Its functions are:carpcarp msgDescriptionWarns of an error; reports the error as having occurred in the calling routine, not in the routine that contains the
carp
.Use Carp; carp "text of error message";
cluckcluck msgDescriptionWarns of errors and prints a stack backtrace; reports the error as having occurred in the calling routine. Not exported by default.use Carp qw(cluck); cluck "text of error message";
confessconfess msgDescriptionDies and prints a stack backtrace. Reports the error as having occurred at the point whereconfess
was called.croakcroak msgDescriptionDies, reporting error as having occurred in the calling routine.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI
- Content preview·Buy reprint rights for this chapterThe CGI (Common Gateway Interface) library permits object-oriented web form creation and processing. The CGI.pm module contains the bulk of functionality for CGI programming. Four subclasses provide interfaces to various server environments and additional features. They are described below. For complete information on how CGI works and a description of CGI.pm see Chapter 9, and Chapter 10.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI::Apache
- Content preview·Buy reprint rights for this chapterSets up the environment for using CGI.pm with the Perl-Apache API. The
new
constructor for this class creates an Apache::CGI class object that interfaces to the API.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI::Carp
- Content preview·Buy reprint rights for this chapterCreates Carp-like CGI routines for writing error messages to the HTTPD or other error log. Exports functions for
warn
,die
,carp
,confess
, andcroak
. The functions write timestamped error messages to your server log or other output that you specify. See Section 8.24 for details on the Carp functions.Two other functions are provided by this module. Neither are automatically exported, so you must explicitly import them inuse
:use CGI::Carp qw(carpout fatalsToBrowser);
carpoutcarpout \*fhDescriptionSends error messages to the filehandle fh. You should provide a reference to the filehandle glob, although you can also just use the filehandle's name for this function.fatalsToBrowserfatalsToBrowserDescriptionWhen this routine is imported viause
, fatal errors, such as those produced bydie
andconfess
, send error messages to the browser as well as the error log. A simple HTTP response is created with the error message, followed by a request to send mail to the web administrator.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI::Cookie
- Content preview·Buy reprint rights for this chapterProvides an interface to Netscape (HTTP/1.1) cookies that can be used in conjunction with CGI.pm or independently. To use CGI::Cookie, you create a new cookie object with the constructor
new
. You can then send the cookie to the browser in one of the following ways:-
From a CGI script, create a Set-Cookie field in the HTTP header for each cookie you want to send (
$c
is the cookie object):print "Set-Cookie: $c0";
-
With CGI.pm (see Chapter 10), use the
header
method with a-cookie
argument:print header(-cookie=>$c);
-
Using mod_perl (see Chapter 11), use the request object's
header_out
method:$r->header_out('Set-Cookie',$c);
The following methods are provided for CGI::Cookie:new$c = new CGI::Cookie( attribs )DescriptionConstructor. Creates a new cookie. Attributes are:-
-domain =
domain_name -
Optional, points to domain name or fully qualified hostname to which cookie will be returned. If missing, browser will return cookie only to the server that set it.
-
-expires =
date -
Optional expiration date, in any of the date formats recognized by CGI.pm. If missing, cookie expires at the end of this browser session.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- CGI::Fast
- Content preview·Buy reprint rights for this chapterCGI interface for FastCGI. FastCGI is a type of gateway for web servers that improves performance by loading scripts as persistently running processes. CGI::Fast provides a
new
constructor to create a CGI object that runs in this environment. FastCGI requires both a server and a version of Perl that are FastCGI enabled. Seewww.fastcgi.com
for more information.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI::Push
- Content preview·Buy reprint rights for this chapterProvides an interface to do server push operations, letting you rewrite pages whose content changes regularly. A server push operation automatically sends updates to a page on a push-capable browser. CGI::Push exports the function
do_push
to implement page redraws. This method can be used on a CGI::Push object or on its own:$q = new CGI::Push; $q->do_push(-next_page => \&sub); # or do_push (-next_page => \&sub);
do_push
requires one argument: a reference to a subroutine that will draw the next page. You may optionally specify a subroutine that draws the last page and the interval between page updates. Additional parameters todo_push
are those that can be used with a CGI::headers object.do_pushdo_push (params)DescriptionImplements a server push operation, which updates a page at specific intervals. Parameters are:-
-delay =>
n -
Specifies the number of seconds, n, to wait before the next call to the page-drawing subroutine.
-
-last_page =>
\&sublast -
Runs the subroutine sublast to draw the last page update of a server push operation. The
-last_page
routine is invoked when the-next_page
routine returns false. A reference to a subroutine glob should be provided for this parameter, but the name of the subroutine is also acceptable. -
-next_page =>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- CGI::Switch
- Content preview·Buy reprint rights for this chapterProvides a
new
method that tries to callnew
in each of the Apache::CGI, CGI::XA, and CGI classes, returning the first CGI object that it successfully gets.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Class::Struct
- Content preview·Buy reprint rights for this chapterFormerly named Class::Template; exports a single function,
struct
.struct
takes a list of element names and types, and optionally a class name, and creates a Perl class that implements a "struct-like" data structure. It also creates a constructor method,new
, for creating objects of the class (so a class created this way must not itself define anew
method).Each element in the struct data has an accessor method, which is used to assign to the element and to fetch its value. The default accessor can be overridden by declaring a sub of the same name in the package. Each element's type can be scalar, array, hash, or class.structstruct (paramlist)DescriptionCreates a class, with object methods for each element of the class. The parameter list paramlist can take one of three forms:struct( CLASS_NAME => [ ELEMENT_LIST ]); # object is array-based struct( CLASS_NAME => { ELEMENT_LIST }); # object is hash-based struct( ELEMENT_LIST ); # class name is current package name # and object is array-based
The array-based element lists are faster and smaller, but the hash-based list is more flexible. The class that is created can be a subclass of the UNIVERSAL class, but not of any other class.Element listThe items in the ELEMENT_LIST are of the form:NAME => TYPE, ...
where eachNAME=>TYPE
pair declares one element of thestruct
. Each element name is defined as an accessor method, unless a method is explicitly defined with that name. (In that case, a warning is issued if the -w flag is set.)Element types and accessor methodsThere are four possible element types, each represented by a string. Each string may start with an asterisk (*
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Config
- Content preview·Buy reprint rights for this chapterUsed to access configuration information. When Perl is built, the Configure script obtains and saves this information in a hash,
%Config
, in Config.pm itself. Config checks to be sure it's running with the same Perl version as the one that created the hash.The index into the hash is the shell variable name.%Config
is always exported; the following three functions are exported on request:config_shconfig_shDescriptionReturns all Perl configuration information.use Config(qw(config_sh)); print config_sh();
returns:archlibexp='sun4-solaris' cc='cc' ccflags='-I/usr/local/include/sfio -I/usr/local/include' ...
config_varsconfig_vars (names)DescriptionReturns the name/value pairs for the requested configuration variables. Prints the results to STDOUT.use Config(qw(config_vars)); print config_vars(qw(osname ccflags));
returns:osname='solaris' ccflags='-I/usr/local/include/sfio -I/usr/local/include'
myconfigmyconfigDescriptionReturns a summary of the major Perl configuration values.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - constant
- Content preview·Buy reprint rights for this chapterA Perl pragma that declares compile-time constants with a given scalar or list value. By default, the value is evaluated in list context, but you can override the default by specifying
scalar
.use constant NAME1 => value1; use constant NAME2 => scalar value2;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CPAN
- Content preview·Buy reprint rights for this chapterLets you access CPAN; search for a module, a bundle, an author, or a distribution; download a module or distribution; install it; and
make
it. The CPAN module can be used either interactively from the command line or programmatically:perl -MCPAN -eshell; #run from the command line
Or:use CPAN; my $obj = CPAN::Shell->install('ExtUtils::MakeMaker');
This section describes the use of the CPAN module from a program. See Chapter 2, for information on using it interactively and for details of the available commands. These commands, available interactively from the shell, are methods of the class CPAN::Shell. From a program, they are available both as methods (e.g.,CPAN::Shell->install(…)
) and as functions in the calling package (e.g.,install(…)
).Each of the commands that produce listings of modules (r
,autobundle
, andu
) returns a list of the IDs of all modules within the list. The IDs of all objects available within a program are strings that can be expanded to the corresponding real objects with theCPAN::Shell->expand("Module",@things)
method.expand
returns a list of CPAN::Module objects according to the@things
arguments. In scalar context, it returns only the first element of the list.The CPAN module contains a session manager, which keeps track of objects that have been fetched, built, and installed in the current session. No status is retained between sessions.There is also a cache manager, which keeps track of disk space used and deletes extra space. The cache manager keeps track of the build directory,$CPAN::Config->{build_dir}
, and uses a simple FIFO mechanism to delete directories belowbuild_dir
when they grow bigger than$CPAN::Config->{build_cache}
.The original distribution files are kept in the directory$CPAN::Config->{keep_source_where}
. This directory is not covered by the cache manager, but must be controlled by the user. If the same directory is used as bothbuild_dir
andkeep_source_where
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CPAN::FirstTime
- Content preview·Buy reprint rights for this chapterThe CPAN::FirstTime module has one function,
init
, which is an initialization routine called automatically the first time a user uses the CPAN module. It asks the user a series of questions, and writes the answers into aCPAN::Config
file.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CPAN::Nox
- Content preview·Buy reprint rights for this chapterA wrapper for CPAN.pm that prevents the use of any compiled extensions while it's executing. Run it in interactive mode if you have upgraded Perl and now your extensions aren't working:
perl -MCPAN::Nox -eshell;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Cwd
- Content preview·Buy reprint rights for this chapterThe Cwd module provides three functions that get the pathname of the current working directory. Using these functions instead of the pwd command will make your code more portable, because not all systems have pwd.cwdcwdDescriptionGets the current working directory. This is the safest way to get it.getcwdgetcwdDescriptionDoes the same thing as
cwd
by reimplementing the C library functionsgetcwd(3)
orgetwd(3)
in Perl.fastcwdfastcwdDescriptionA faster way to get the directory, but somewhat more dangerous because of the way it works internally.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Data::Dumper
- Content preview·Buy reprint rights for this chapterConverts Perl data structures into strings that can be printed or used with
eval
to reconstruct the original structures. Takes a list of scalars or reference variables and writes out their contents in Perl syntax. Several interfaces to Data::Dumper are provided:-
Simple procedural interface:
print Dumper($foo, $bar);
-
Extended usage with names:
print Data::Dumper->Dump([$foo, $bar], [qw(foo *ary)]);
-
Object-oriented interface:
$d = Data::Dumper->new([$foo, $bar], [qw(foo *ary)]); ... print $d->Dump;
By default, references are identified as$VAR
n, where n is a numeric suffix. References to substructures within$VAR
n are labeled using arrow notation. In the extended usage form, references can be given user-specified names. See the Data::Dumper manpage for examples of the module's use.Several configuration variables can be used to control the output generated using the procedural interface. These variables control the default state of the object created by the new method. Each variable has a corresponding method that can be used later to query or modify the object. In the following list, each variable is followed by the corresponding method:-
$Data::Dumper::Bless
-
$obj->Bless([
newval])
-
Can be set to a string that specifies an alternative to the
bless
builtin operator used to create objects. A function with the specified name should exist and should accept the same arguments as the builtin. Default isbless
. -
$Data::Dumper::Deepcopy
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- DB_File
- Content preview·Buy reprint rights for this chapterTies a Perl hash to one of the Berkeley DB database types and lets you use functions provided in the DB API:
[$X =] tie %hash, "DB_File", $filename [, $flags, $mode, $DB_HASH]; [$X =] tie %hash, "DB_File", $filename, $flags, $mode, $DB_BTREE; [$X =] tie @array, "DB_File", $filename, $flags, $mode, $DB_RECNO;
The types are:-
$DB_HASH
-
Stores key/data pairs in data files; equivalent to other hashing packages like DBM, NDBM, ODBM, GDBM, and SDBM.
-
$DB_BTREE
-
Stores key/data pairs in a binary tree.
-
$DB_RECNO
-
Uses a record (line) number to access fixed-length and variable-length flat text files through the same key/value-pair interface as in
$DB_HASH
and$DB_BTREE
.
After you'vetie
d a hash to a database:$db = tie %hash, "DB_File", "filename";
you can access the Berkeley DB API functions:$db->put($key, $value, R_NOOVERWRITE); # invoke the DB "put" function
All the functions defined in the dbopen(3) manpage are available exceptclose
anddbopen
itself. The constants defined in the dbopen manpage are also available.Here are the functions available (the comments note only the differences from the equivalent C function):del$X ->del(key[, flags])DescriptionRemoves key/value pairs from the database. flags is optional.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Devel::SelfStubber
- Content preview·Buy reprint rights for this chapterGenerates stubs in a module that uses the SelfLoader, either printing the necessary stubs or generating the whole module with the stubs inserted in the correct location before the
__DATA__
token. The default is to just print the stubs.stubstub (module[, dir])DescriptionGenerates the stubs. Takes the following arguments:- module
-
Name of the module, in the form Devel::SelfStubber (with no .pm at the end).
- dir
-
Library directory that contains the module; defaults to the current directory.
To just print the stubs:use Devel::SelfStubber; Devel::SelfStubber->stub(module, dir);
To generate the whole module, with the stubs inserted correctly, set the variable$Devel::SelfStubber::JUST_STUBS
to 0:use Devel::SelfStubber; $Devel::SelfStubber::JUST_STUBS = 0; Devel::SelfStubber->stub(module, dir);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - diagnostics
- Content preview·Buy reprint rights for this chapterProvides more descriptive diagnostics than those generated by the Perl compiler and interpreter. Uses the longer, more explanatory error messages found in the perldiag manpage. Can be used as a pragma or as a standalone program, splain. When used as a pragma, diagnostics affects the compilation phase of your program as well as the execution phase. As a standalone module, it is used to post-process errors after execution has completed.The splain program links to diagnostics.pm to act on the standard error output of a Perl program. The program's output can be sent to a file, which is then used as input to splain, or it can be piped directly to splain. Output from splain is directed to STDOUT.
- -p
-
Sets the variable
$diagnostics::PRETTY
to true. - -v
-
Prints the perldiag manpage introduction, then any diagnostic messages.
As a pragma:use diagnostics [-verbose]
enables the use ofdiagnostics
in your program (and enables Perl's -w flag). Compilation is then subject to the enhanced diagnostics, which are issued to STDERR. Set thediagnostics::PRETTY
variable in a BEGIN block to provide nicer escape sequences for pagers, so your output looks better. The-verbose
option prints the perldiag manpage introduction, then any diagnostic messages. Functions are:-
enable
-
Turns diagnostics on at runtime.
-
disable
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - DirHandle
- Content preview·Buy reprint rights for this chapterProvides methods for accessing Perl's directory functions, avoiding namespace pollution. Creates anonymous glob to hold a directory handle and closes the dirhandle automatically when the last reference goes out of scope. The methods provided are:new$dh = new DirHandle [dirname]DescriptionConstructor. Creates a new directory handle. The optional directory name, dirname, defaults to the current directory.close$dh ->close()DescriptionCloses a directory handle; equivalent to the
closedir
function.open$dh ->open(dirname)DescriptionOpens directory dirname; equivalent to theopendir
function.read$dh ->read()DescriptionReads directory entries. Equivalent to thereaddir
function. In scalar context, reads the next directory entry; in list context, reads all entries.rewindAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - DynaLoader
- Content preview·Buy reprint rights for this chapterThe standard Perl interface to the dynamic linking mechanisms available on many platforms.Use DynaLoader like this:
package Module; require DynaLoader; @ISA = qw(... DynaLoader ...); bootstrap Module;
Thebootstrap
method calls your module's bootstrap routine directly if the module is statically linked into Perl. Otherwise the module inherits thebootstrap
method from DynaLoader, which loads in your module and calls itsbootstrap
method.If you want to extend DynaLoader to a new architecture, you need to know about its internal interface. The variables it uses are:-
$dl_debug
-
Enables internal debugging messages on the Perl side of the DynaLoader; by default, is set to
$ENV{'PERL_DL_DEBUG'}
if that is defined. A similar debugging variable is added to the C code (see dlutils.c) and enabled if Perl was built with the -DDEBUGGING flag, or it can be set via thePERL_DL_DEBUG
environment variable. Set to1
for minimal information or higher for more detail. -
@dl_library_path
-
Default list of directories to search for libraries; initialized to hold the list of directories in
$Config{'libpth'}
. Should also be initialized with other directories that can be determined from the environment at runtime. -
@dl_resolve_using
-
List of additional libraries or other shared objects for resolving undefined symbols. Required only on platforms without automatic handling for dependent libraries.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- English
- Content preview·Buy reprint rights for this chapterProvides aliases for the Perl built-in special variables. Everything else about the variables and their use remains the same. Be aware, though, that using the English module significantly slows down a program for regular expressions.Some of the Perl variables match some awk built-in variables. For those cases, you'll find two English names: a short version (which is the awk name) and a longer version. For example, you can use either
$ERRNO
(the awk name) or$OS_ERROR
to refer to the Perl variable$!
.Here is the list of variables, and their English alternatives:Perl English Perl English @_
@ARG
$?
$CHILD_ERROR
$_
$ARG
$!
$OS_ERROR
$%
$MATCH
$!
$ERRNO
$`
$PREMATCH
$@
$EVAL_ERROR
$'
$POSTMATCH
$$
$PROCESS_ID
$+
$LAST_PAREN_MATCH
$$
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Env
- Content preview·Buy reprint rights for this chapterLets your program treat environment variables as simple variables instead of having to access them from the
%ENV
pseudo-hash where they are kept.use Env; use Env qw(var1 var2 ...);
Internally, Env uses animport
function that ties suitably named environment variables to global Perl variables with the same names. By default, it ties all variables yielded bykeys %ENV
. A "suitable" environment has a name that begins with an alphabetic character and contains only alphanumeric characters or underscores.Whenuse Env
is invoked with arguments, the arguments are interpreted as a list of environment variables totie
, but the variables don't have to exist yet. After a variable has been tied, you can use it like a normal variable, accessing or changing its value.You untie a variable by setting its value toundef
.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Errno
- Content preview·Buy reprint rights for this chapterProvides system errno constants from errno.h include file. Defines and conditionally exports all the error constants defined in errno.h. There is one export tag, :POSIX, which exports all POSIX-defined error numbers.The file Errno.pm is automatically generated and shouldn't be updated. Any changes made to the file will be lost.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Exporter
- Content preview·Buy reprint rights for this chapterImplements a default import method for other modules to inherit if they don't want to define their own. If you are writing a module, you can do the following:
package Module; use Exporter (); @ISA = qw(Exporter); @EXPORT = qw(...); @EXPORT_OK = qw(...); %EXPORT_TAGS = (tag => [...]);
where@EXPORT
is a list of symbols to export by default,@EXPORT_OK
is a list of symbols to export on request, and%EXPORT_TAGS
is a hash that defines names for sets of symbols. Names in%EXPORT_TAGS
must also appear in@EXPORT
or@EXPORT_OK
.Then Perl programs that want to use your module just say:use Module; # Import default symbols use Module qw(...); # Import listed symbols use Module (); # Do not import any symbols
The Exporter can handle specialized import lists. An import list is the list of arguments passed to theimport
method. If the first entry begins with!
,:
, or/
, the list is treated as a series of specifications that add to or delete from the list. A leading!
means delete, rather than add.Symbol Meaning [!]
nameThis name only[!]:DEFAULT
All names in @EXPORT
[!]:
tagAll names in$EXPORT_TAGS{
tag}
anonymous list[!]/
pattern/
All names in@EXPORT
and@EXPORT_OK
that match patternExporter methods are:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Command
- Content preview·Buy reprint rights for this chapterProvided with the standard Win32 port to replace common Unix commands in MakeFiles. Includes subroutines for the following commands:catcat file... [> destination]DescriptionConcatenates all specified files into destination file or to STDOUT.chmodchmod mode files...DescriptionSets Unix-like permissions on all files specified, where mode gives the permissions to set.cpcp source... destinationDescriptionCopies a single source file source to destination. Multiple source files can be specified if destination is an existing directory.eqtimeeqtime source destinationDescriptionSets the "modified time" of destination to that of source.mkpathmkpath directory...DescriptionCreates directory, including any parent directories.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Embed
- Content preview·Buy reprint rights for this chapterGenerally called from the Makefile that builds your application to provide initialization functions for embedding Perl code in C or C++ applications. For example:
perl -MExtUtils::Embed -e xsinit perl -MExtUtils::Embed -e ldopts
Uses the configuration information kept in Config.pm (see the Config module, above). Exports the following functions:ccdlflagsccdlflagsDescriptionPrints$Config{ccdlflags}
.ccflagsccflagsDescriptionPrints$Config{ccflags}
.ccoptsccoptsDescriptionCombinesperl_inc
,ccflags
, andccdlflags
.ldoptsldoptsDescriptionOutputs arguments for linking the Perl library and extensions to your application. When invoked as:perl -MExtUtils::Embed -e ldopts -
the following options are recognized:- -std
-
Output arguments for linking the Perl library and any extensions linked with the current Perl.
- -I <path1:path2>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Install
- Content preview·Buy reprint rights for this chapterUsed by MakeMaker for handling the platform-dependent installation and deinstallation of modules; not meant to provide general-purpose tools. Exports the following functions:installinstall (\hashref, verbose, nonono)DescriptionInstalls files. Takes the following arguments:
- \hashref
-
Reference to a hash, where each key is a directory to copy from and the value is the directory to copy into. The whole tree below the "from" directory is copied, with timestamps and permissions preserved.The hash has two additional keys:
read
andwrite
. After copying everything,install
writes the list of target files to the file named by$hashref->{write}
. If there is another file named by$hashref->{read}
, its contents are merged into the written file.
install_defaultinstall_default ([fullext])DescriptionCallsinstall
with the same arguments as the MakeMaker defaults. Takes zero or one argument. With no argument, it treats$ARGV[0]
as the argument. If present, the argument contains the value of MakeMaker's FULLEXT key.pm_to_blibpm_to_blib (\hashref[, dir])DescriptionTakes a hash reference as the first argument and copies all the keys of the hash to the corresponding values. Filenames with theAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Installed
- Content preview·Buy reprint rights for this chapterProvides inventory management for installed modules, based on the contents of the .packlist files that are created during installation. It also permits classifying the installed files and extracting directory information from the .packlist files.new$inst = ExtUtils::Installed->new()DescriptionSearches for all installed .packlists on the system and stores their contents. Takes no parameters, uses ExtUtils::Packlist to read the .packlist files.directories$inst ->directories(module[, string[, dir[,...]]])DescriptionReturns list of directories. Only returns directories that contain files from the specified module. Parameters are:
- module
-
Required. The name of a module; returns a list of all directories in the package.
- string
-
Optional. Possible values are
prog
,man
, orall
to return program directories, manual directories, or all directories, respectively. - dir
-
Optional. One or more directories. If specified, only directories under the specified directories are returned.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Liblist
- Content preview·Buy reprint rights for this chapterUsed for building a Makefile for a Perl module. Takes a list of libraries and returns platform-appropriate lines that can be included in the Makefile.
require ExtUtils::Liblist; ExtUtils::Liblist::ext($potential_libs[, $verbose]);
The input list $potential_libs is in the form -llib1 -llib2 -llib3. Additional library paths may be included in the form -L/another/path, which affects searches for all subsequent libraries. If the Boolean $verbose is specified, verbose output messages are provided. Returns a list of four scalar values:- EXTRALIBS
-
List of libraries that need to be linked with ld when linking a Perl binary that includes a static extension.
- LDLOADLIBS
-
List of static or dynamic libraries that can or must be linked when creating a shared library using ld.
- LD_RUN_PATH
-
Colon-separated list of the directories in LDLOADLIBS.
- BSLOADLIBS
-
List of libraries that are needed but can be linked in dynamically with the DynaLoader at runtime.
The Win32 version (in the standard Perl distribution) has several differences from the Unix-OS/2 version:-
-l and -L are not required on the library and path specifications.
-
Entries must be libraries, not plain object files.
-
If $potential_libs is empty, the return value is also empty.
-
The specified libraries can include both static and import libraries.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::MakeMaker
- Content preview·Buy reprint rights for this chapterWrites a Makefile for use during module installation. Provides a function,
WriteMakefile
, which creates an object whose attributes are set from various sources and which actually writes the Makefile. See Chapter 2 for information about the use of the Makefile and MakeMaker during module installation. This section explains the details of actually creating the Makefile with MakeMaker. It assumes an understanding of make and Makefiles.If you are a Perl programmer writing a module, you should run h2xs to generate the template for your module. Among other things, h2xs creates a file called Makefile.PL, and it's Makefile.PL that runs MakeMaker. On the other hand, if you are installing a module, you can usually just run the Makefile.PL that came with the module, perhaps adding a PREFIX argument if you are installing the module locally (see Chapter 2). In either case, you shouldn't need to run ExtUtils::MakeMaker directly unless you have special requirements.A typical call to MakeMaker might look like this example from the CGI distribution:use ExtUtils::MakeMaker; WriteMakefile( NAME => "CGI", DISTNAME => "CGI-modules", VERSION => "2.76", linkext => { LINKTYPE => '' }, dist => {COMPRESS=>'gzip -9f', SUFFIX => 'gz'}, );
MakeMaker attributes can be passed as arguments toWriteMakefile
, as in the example, or they can be passed as name=value pairs on the command line:perl Makefile.PL PREFIX=/home/mydir/Perl/Modules
To see what MakeMaker is doing, you can say:perl Makefile.PL verbose
The following attributes can be specified:- C
-
Reference to array of *.c filenames. Initialized from a directory scan and the values portion of the XS attribute hash. Not currently used by MakeMaker but may be handy in Makefile.PLs.
- CCFLAGS
-
String to be included in the compiler call command line between the INC and OPTIMIZE arguments.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Manifest
- Content preview·Buy reprint rights for this chapterProvides utilities for maintaining and using a MANIFEST file. The MANIFEST file is essentially a packing list, included with a module, so the user who installs the module can be sure that all the files are actually present. The file created by ExtUtils::Manifest is a list of filenames, one per line, with an optional comment on each line.ExtUtils::Manifest optionally uses a file called MANIFEST.SKIP, which contains regular expressions specifying files that are not to be included in MANIFEST. Manifest also defines two global variables that are used by several of the functions:
-
$ExtUtils::Manifest::MANIFEST
-
The name of the MANIFEST file. Changing the value results in different MANIFEST and different MANIFEST.SKIP files. Default is MANIFEST.
-
$ExtUtils::Manifest::Quiet
-
If true, the functions work silently. Default is 0.
Provides six functions, which are exportable on request:filecheckfilecheckDescriptionFinds files below the current directory that are not mentioned in the MANIFEST file. Consults MANIFEST.SKIP for files that shouldn't be included.fullcheckfullcheckDescriptionDoes bothmanicheck
andfilecheck
.manicheckAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- ExtUtils::Miniperl
- Content preview·Buy reprint rights for this chapterGenerates a file, perlmain.c, that contains the bootstrap code to make the modules associated with the libraries available from within Perl. ExtUtils::Miniperl itself is generated automatically from a script called minimod.PL when Perl is built; typically, it is used from within a Makefile generated by ExtUtils::MakeMaker rather than being called directly. The module exports one subroutine:writemainwritemain (dirs)DescriptionTakes an argument list of directories that contain archive libraries needed by Perl modules and writes the file to be compiled as perlmain.c to STDOUT.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Mkbootstrap
- Content preview·Buy reprint rights for this chapterTypically called from a module's Makefile. It writes a *.bs file that is needed by some architectures to do dynamic loading.
use ExtUtils::Mkbootstrap; mkbootstrap();
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Mksymlists
- Content preview·Buy reprint rights for this chapterProduces option files used by some operating systems' linkers during creation of shared libraries for dynamic extensions. Normally called from a Makefile when a module is built; it exports one function:MksymlistsMksymlists (varlist)DescriptionCreates the linker option file. The varlist argument is a list of key/value pairs; for example:
use ExtUtils::Mksymlists; Mksymlists({ NAME => $name, DL_VARS => [$var1, $var2, $var3], DL_FUNCS => [$pkg1 => [$func1, $func2], $pkg2 => [$func3]});
Valid keys are:-
DLBASE
-
The name by which the linker knows the module. If not specified, it is derived from the NAME attribute. Currently used only by OS/2.
-
DL_FUNCS
-
Identical to the MakeMaker DL_FUNCS attribute and usually taken from it. Its value is a reference to a hash, where each key is a package name and each value is a reference to an array of function names to be exported by the module.
-
DL_VARS
-
Identical to the MakeMaker DL_VARS attribute, and usually taken from it. Its value is a reference to an array of variable names to be exported by the extension.
-
FILE
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- ExtUtils::MM_OS2
- Content preview·Buy reprint rights for this chapterProvides methods for use with MakeMaker for OS2 systems. Used internally by MakeMaker if needed. See ExtUtils::MM_Unix for documentation of the methods provided there. Overrides the implementation of the methods, not the interface.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::MM_Unix
- Content preview·Buy reprint rights for this chapterProvides methods for MakeMaker to handle portability issues. You never need to
require
this module, but you might want to if you are working on improving MakeMaker's portabilityProvides methods for both Unix and non-Unix systems; on non-Unix systems, they can be overridden by methods defined in other MM_* modules. The methods are listed here:catdircatdir listDescriptionConcatenates a list of directory names to form a complete path ending with a directory. On Unix, joins the names with/
.catfilecatfile listDescriptionConcatenates one or more directory names and a filename to form a complete path ending with a filename. On Unix, joins the names with/
.dir_targetdir_target arrayDescriptionTakes an array of required directory names and returns a Makefile entry to create an .exists file in the directories. Returns nothing if the entry has already been processed.file_name_is_absoluteAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::MM_VMS
- Content preview·Buy reprint rights for this chapterProvides methods for use with MakeMaker for VMS systems. Used internally by MakeMaker if needed. See ExtUtils::MM_Unix for documentation of the methods provided there. Overrides the implementation of the methods, not the interface.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::MM_Win32
- Content preview·Buy reprint rights for this chapterProvides methods for use with MakeMaker for Win32 systems. Used internally by MakeMaker in the standard Win32 Perl distribution if needed. See ExtUtils::MM_Unix for a documentation of the methods provided there. Overrides the implementation of these methods, not the interface.catfilecatfileDescriptionConcatenates one or more directory names and a filename to form a complete path, ending with a filename.constantsconstantsDescriptionInitializes constants, .SUFFIXES, and .PHONY.static_libstatic_libDescriptionDefines how to produce the *.a (or equivalent) files.dynamic_bsdynamic_bsDescriptionDefines targets for bootstrap files.dynamic_libdynamic_libDescriptionDefines how to produce the *.so (or equivalent) files.canonpathcanonpathAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::Packlist
- Content preview·Buy reprint rights for this chapterManages .packlist files. Supports an extended .packlist format. The original format is a list of absolute pathnames, one pathname per line. In the extended format, each line can also contain a list of attributes as key/value pairs, which are used by the installperl script. For example:
/usr/local/bin/perl from=/usr/local/pbeta/bin/perl5.005 type=link /usr/local/bin/perl5.005 type=file /usr/local/lib/perl5/5.005/AnyDBM_File.pm type=file
Also see ExtUtils::Installed.new$pl = ExtUtils::Packlist->new([plfile])DescriptionConstructor. Takes the name of a .packlist as the optional parameter and returns a reference to a hash that has an entry for each line in the .packlist. The value associated with each key isundef
for oldstyle .packlists. For files in the extended format, the value for each key is a hash containing the key/value pairs on the line associated with that key.packlist_file$pl ->packlist_file()DescriptionReturns the name of the associated .packlist file.read$pl ->read([plfile])DescriptionReads the .packlist specified by the plfile parameter if given; otherwise reads the file associated with $pl. CallsCarp::croak
if the file doesn't exist.validateAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ExtUtils::testlib
- Content preview·Buy reprint rights for this chapterUsed for testing a module after it's been built and before it's been installed, when you don't want to (or can't) run make test. Adding:
use ExtUtils::testlib;
to your test program causes the intermediate directories used by make to be added to@INC
, allowing you to run the test.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Fatal
- Content preview·Buy reprint rights for this chapterProvides a way to replace functions that return false on failure with equivalents that die instead, so you can use the functions without having to test the return values explicitly. Fatal reports errors via
die
; you can trap them with$SIG{__DIE__}
if you want to take some action before the program exits. You can use Fatal for both user-defined functions and Perl core operators exceptexec
andsystem
.importimport Fatal functionDescriptionWraps function in an equivalent function that willdie
on failure.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Fcntl
- Content preview·Buy reprint rights for this chapterA translation of the C fcntl.h program that uses h2xs (which builds a Perl extension from a C header file) and the C compiler to translate
#define
symbols and make them available as functions. Exports the following routines by default; each routine returns the value of the#define
that is the same as the routine name:FD_CLOEXEC
F_DUPFD
F_GETFD
F_GETFL
F_GETLK
F_RDLCK
F_SETFD
F_SETFL
F_SETLK
F_SETLKW
F_UNLCK
F_WRLCK
O_APPEND
O_CREAT
O_EXCL
O_NDELAY
O_NOCTTY
O_NONBLOCK
O_RDONLY
O_RDWR
O_TRUNC
O_WRONLY
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - fields
- Content preview·Buy reprint rights for this chapterPragma that provides the ability to define class fields at compile time, by updating the
%FIELDS
hash in the calling package. The%FIELDS
hash is set up at compile time as well; use thebase
pragma to copy fields from base classes, and thenfields
to add new fields. Lets you have objects with named fields that are as compact and fast as arrays to access. For more details, see the fields manpage and the pseudo-hash section of the perlref manpage.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Basename
- Content preview·Buy reprint rights for this chapterParses a file's path, returning its three component pieces: the path to the file, the file's basename, and the file's extension. For example, for:
/usr/local/lib/perl5/SelectSaver.pm
the path is /usr/local/lib/perl5, the basename is SelectSaver, and the extension is .pm. File::Basename exports the following functions:basenamebasename (fullname[, suffixlist])DescriptionReturns the first element of the list that would be produced if you calledfileparse
with the same arguments. Provides compatibility with the Unix basename command. Takes the following arguments:- fullname
-
Input file specification
- suffixlist
-
Optional list containing patterns to be matched against the end of fullname to find the suffix
dirnamedirname (fullname)DescriptionReturns the directory portion of the input file specification. fullname is the input file specification.fileparsefileparse (fullname[, suffixlist])DescriptionDivides a file specification into its three parts, returning them in the order: filename, path, suffix.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::CheckTree
- Content preview·Buy reprint rights for this chapterRuns file tests on a set of files. Exports one function,
validate
, which takes a single multi-line string as input. Each line of the string contains a filename plus a test to run on the file. The test can be followed with|| die
to make it a fatal error if it fails. The default is|| warn
. Prepending!
to the test reverses the sense of the test. You can group tests (e.g.,-rwx
); only the first failed test of the group produces a warning. For example:use File::CheckTree; $warnings += validate( q{ /vmunix -e || die /bin cd csh !-ug sh -ex /usr -d || warn "What happened to $file?\n" });
Available tests include all the standard Perl file-test operators except -t, -M, -A, and -C. Unless it dies,validate
returns the number of warnings issued.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Compare
- Content preview·Buy reprint rights for this chapterCompares the contents of two sources, each of which can be a file or a filehandle. Returns
0
if the sources are equal,1
if they are unequal, and-1
on error. File::Compare provides two functions:comparecompare (file1, file2[, buffsize])DescriptionCompares file1 to file2. Exported by default. If present, buffsize specifies the size of the buffer to use for the comparison.cmpcmp (file1, file2[, buffsize])Descriptioncmp
is a synonym forcompare
. Exported on request.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Copy
- Content preview·Buy reprint rights for this chapterCopies or moves files or filehandles from one location to another. Returns
1
on success,0
on failure, or sets$!
on error.copycopy (source, dest[, buffsize])DescriptionCopies source to dest. Takes the following arguments:- source
-
The source string, FileHandle reference, or FileHandle glob. If source is a filehandle, it is read from; if it's a filename, the filehandle is opened for reading.
- dest
-
The destination string, FileHandle reference, or FileHandle glob. dest is created if necessary and written to.
- buffsize
-
Specifies the size of the buffer to be used for copying. Optional.
cpcp (source, dest[, buffsize])DescriptionLikecopy
, but exported only on request.use File::Copy "cp"
movemove (source, dest)DescriptionAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::DosGlob
- Content preview·Buy reprint rights for this chapterProvides a portable enhanced DOS-like globbing for the standard Perl distribution. DosGlob lets you use wildcards in directory paths, is case-insensitive, and accepts both backslashes and forward slashes (although you may have to double the backslashes). Can be run three ways:
-
From a Perl script:
require 5.004 use File::DosGlob 'glob'; @perlfiles = glob "..\pe?l/*.p?"; print <..\pe?l/*.p?>;
-
With the perl command, on the command line:
# from the command line (overrides only in main::) % perl -MFile::DosGlob=glob -e "print <../pe*/*p?>"
-
With the perlglob.bat program on the DOS command line:
% perlglob ../pe*/*p?
When invoked as a program from the command line, File::DosGlob prints null-separated filenames to STDOUT.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- File::Find
- Content preview·Buy reprint rights for this chapterLooks for files that match a particular expression. Exports two functions:findfind (\&wanted, dir1[, dir2 ...])DescriptionWorks like the Unix find command; traverses the specified directories, looking for files that match the expressions or actions you specify in a subroutine called
wanted
, which you must define. For example, to print out the names of all executable files, you could definewanted
this way:sub wanted { print "$File::Find::name\n" if -x; }
Provides the following variables:-
$File::Find::dir
-
Current directory name (
$_
has the current filename in that directory). -
$File::Find::name
-
Contains
"$File::Find::dir/$_"
. You are chdired to$File::Find::dir
whenfind
is called. -
$File::Find::prune
-
If true,
find
does not descend into any directories. -
$File::Find::dont_use_nlink
-
Set this variable if you're using the Andrew File System (AFS).
finddepthAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- File::Path
- Content preview·Buy reprint rights for this chapterCreates and deletes multiple directories with specified permissions. Exports two methods:mkpathmkpath (path, bool, perm)DescriptionCreates a directory path and returns a list of all directories created. Takes the following arguments:
- path
-
Name of the path or reference to a list of paths to create.
- bool
-
Boolean. If true,
mkpath
prints the name of each directory as it is created. Default is false. - perm
-
Numeric mode indicating the permissions to use when creating the directories. Default is
0777
.
rmtreermtree (root, prt, skip)DescriptionDeletes subtrees from the directory structure, returning the number of files successfully deleted. Symbolic links are treated as ordinary files. Takes the following arguments:- root
-
Root of the subtree to delete or reference to a list of roots. The roots, and all files and directories below each root, are deleted.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Spec
- Content preview·Buy reprint rights for this chapterPerforms common operations on file specifications in a portable way. To do that, it automatically loads the appropriate operating-system-specific module, which is one of File::Spec::Mac, File::Spec::OS2, File::Spec::Unix, File::Spec::VMS, or File::Spec::Win32. The complete reference of available functions is given in File::Spec::Unix; the functions are inherited by the other modules and overridden as necessary. Subroutines should be called as class methods, rather than directly.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Spec::Mac
- Content preview·Buy reprint rights for this chapterFile::Spec for MacOS.canonpathFile::Spec->canonpathDescriptionNothing to do; returns what it's given.catdirFile::Spec->catdir( dir[, dir...])DescriptionConcatenates two or more directory names to form a complete path. Ends with a directory name and appends a trailing
:
if there isn't one. You can get a relative path by either beginning the first argument with:
or putting"carview.php?tsp="
as the first argument.catfileFile::Spec->catfile( dir[, dir...], file)DescriptionConcatenates one or more directory names and a filename to form a complete path that ends with a filename. Usescatdir
.curdirFile::Spec->curdirDescriptionReturns string representing the current directory.file_name_is_absoluteFile::Spec->file_name_is_absolute( pathAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Spec::OS2
- Content preview·Buy reprint rights for this chapterFile::Spec for OS/2. Overrides the implementation of the File::Spec::Unix methods, but not the interface.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Spec::Unix
- Content preview·Buy reprint rights for this chapterFile::Spec for Unix. Provides methods for File::Spec to use in manipulating file specifications.canonpathFile::Spec->canonpathDescriptionDoes logical cleanup of path.catdirFile::Spec->catdir(dir[, dir...])DescriptionConcatenates two or more directory names to form a complete path. Ends with a directory name.catfileFile::Spec->catfile(dir[, dir...], file)DescriptionConcatenates one or more directory names and a filename to form a complete path that ends with a filename.curdirFile::Spec->curdirDescriptionReturns
.
, representing the current directory.file_name_is_absoluteFile::Spec->file_name_is_absolute( path )DescriptionTakes a path as argument and returns true if it is an absolute path.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Spec::VMS
- Content preview·Buy reprint rights for this chapterFile::Spec for VMS. Overrides the implementation of the File::Spec::Unix methods, but not the interface.catdirFile::Spec->catdir( dirspecs )DescriptionConcatenates a list of directories and returns the result as a VMS-syntax directory specification.catfileFile::Spec->catfile( filespecs )DescriptionConcatenates a list of file specifications and returns the result as a path.curdirFile::Spec->curdirDescriptionReturns string representing the current directory.file_name_is_absoluteFile::Spec->file_name_is_absolute( path )DescriptionTakes a path as argument and returns true if it is an absolute path. Checks for VMS directory specification as well as Unix separators.pathAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::Spec::Win32
- Content preview·Buy reprint rights for this chapterFile::Spec for Win32. Overrides the implementation of the File::Spec::Unix methods, but not the interface.canonpathFile::Spec->canonpathDescriptionPerforms logical cleanup of a path, doesn't physically check the filesystem.catfileFile::Spec->catfile( dir[, dir...], file )DescriptionConcatenates one or more directory names and a filename to form a complete path that ends with a filename.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - File::stat
- Content preview·Buy reprint rights for this chapterProvides the same file status information as the Perl functions
stat
andlstat
. Exports two functions that return File::stat objects. The objects have methods that return the equivalent fields from the Unix stat(2) call:Field Meaning dev
Device number of filesystem ino
Inode number mode
File mode nlink
Number of links to the file uid
Numeric user ID of owner gid
Numeric group ID of owner rdev
Device identifier size
Size of file, in bytes atime
Last access time mtime
Last modified time ctime
Inode change time blksize
Preferred blocksize for filesystem I/O blocks
Number of blocks allocated You can access the status fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and then accessing them by prependingst_
to the field name (e.g.,$st_mode
). Here are examples of doing it both ways:use File::stat; $stats = stat($file); print $stats->uid; print $st_uid;
statstat (file)DescriptionReturns status information for the file or filehandle pointed to by file. If file is a symbolic link, returns the information for the file that the link points to.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - FileCache
- Content preview·Buy reprint rights for this chapterCloses and re-opens files as necessary so you can always write to a file even if you already have the maximum number of files open. Exports one function:cacheoutcacheout (path)DescriptionMakes sure the file at path is created and accessible through the filehandle also named path. You don't need to invoke
cacheout
between successive accesses to the same file.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - FileHandle
- Content preview·Buy reprint rights for this chapterProvides object methods for working with filehandles. Provides the following methods:new$fh = new FileHandle [filename[, mode]]DescriptionConstructor. Creates a FileHandle, which is a reference to a newly created symbol. The optional parameters, filename and mode, are passed to
open
. The FileHandle object is returned if the open succeeds, otherwise it is destroyed.new_from_fd$fh = new_from_fd FileHandle fd, modeDescriptionConstructor. Creates a FileHandle, but it takes the file descriptor, fd, instead of filename as a parameter, along with mode; the parameters are required.fdopen$fh ->fdopen fdname [openmode]DescriptionLikeopen
, except that its first parameter is not a filename but a filehandle name, a FileHandle object, or a file descriptor number.getpos$pos = $fh ->getposDescriptionIf the C functionsfgetpos(3)
andfsetpos(3)
are available,getpos
returns the current position, $pos, of the FileHandle.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - FindBin
- Content preview·Buy reprint rights for this chapterFinds the full path to a script's bin directory, letting you use relative paths to that directory without needing to know the actual location:
use FindBin; use lib "$FindBin::Bin/../lib";
or:use FindBin qw($Bin); use lib "$Bin/../lib";
FindBin exports the following variables:-
$Bin
-
Path to bin directory from which script was invoked.
-
$Script
-
Basename of script from which Perl was invoked.
-
$RealBin
-
$Bin
with all links resolved. -
$RealScript
-
$Script
with all links resolved.
If you invoke Perl with the -e option or read the Perl script from STDIN, then FindBin sets both$Bin
and$RealBin
to the current directory.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- GDBM_File
- Content preview·Buy reprint rights for this chapterAllows Perl programs to make use of the facilities provided by the GNU
gdbm
library. Most of the libgdbm.a functions are available as methods of the GDBM_File interface. See the gdbm(3) manpage and the description of DB_File in this chapter. The following is an example of the use of GDBM_File:use GDBM_File; tie %hash, "GDBM_File", $filename, &GDBM_WRCREAT, 0644); # read/writes of %hash are now read/writes of $filename untie %hash;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Getopt::Long
- Content preview·Buy reprint rights for this chapterLets your program accept command-line options with long names, introduced by
--
. Standard single-character options are also accepted. Options that start with--
may have an argument appended, following a space or an equals sign (=
):--foo=bar --foo bar
Provides two functions:GetOptions
andconfig
.GetOptions$result = GetOptions( option-descriptions )DescriptionUses descriptions from option-descriptions to retrieve and process the command-line options with which your Perl program was invoked. The options are taken from@ARGV
. AfterGetOptions
has processed the options,@ARGV
contains only command-line arguments that were not options. Returns 0 if errors are detected. Each option description consists of two elements:- Option specifier
-
Defines the option name and optionally a value as an argument specifier.
- Option linkage
-
A reference to a variable that is set when the option is present.
GetOptions
can also take as a first argument a reference to a hash that describes the linkage for the options. The linkage specified in the argument list takes precedence over the one specified in the hash. Thus the following are equivalent:%optctl = (size => \$offset); &GetOptions(\%optctl, "size=i");
and:&GetOptions("size=i" => \$offset);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Getopt::Std
- Content preview·Buy reprint rights for this chapterProcesses single-character command-line options with option clustering. Exports two functions, which analyze
@ARGV
, extract information about the options, and return this information to your program in a set of variables. Processing of@ARGV
stops when an argument without a leading-
is encountered, if that argument is not associated with a preceding option. Otherwise,@ARGV
is processed to the end and left empty.getoptgetopt ('switches'[, \%opts])Descriptionswitches is a string of the command-line options that take arguments. For each option,getopt
sets$opt_
x (where x is the switch) to the value entered as an argument. If \%opts is specified, it is a reference to a hash in whichgetopt
sets the key to the name of the switch and the value to the argument (and the$opt_
variables are not set).getoptsgetopts ('switches'[, \%opts])DescriptionLikegetopt
, except that all valid options are included in switches and options that take an argument are followed by a colon (:
), e.g.:getopt('oDI') # -o, -D, & -I take arguments; there may be other options getopts('o:DI') # -o, -D, and -I are the only valid options; only -o # takes an argument
\%opts means the same as withgetopt
.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - I18N::Collate
- Content preview·Buy reprint rights for this chapterThe use of I18N::Collate is now deprecated, although it is still provided for compatibility with older programs. Don't use it in new programs, as its functionality was integrated into the core Perl in Perl 5.004. See the
locale
pragma.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - integer
- Content preview·Buy reprint rights for this chapterPragma that tells the compiler to use integer operations from here to the end of the enclosing block. Improves processing time on systems without floating-point hardware support.
use integer; $x = 10/3; # $x is now 3, not 3.33333333333333333
Use theno
integer
directive to turn offinteger
inside an inner block.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO
- Content preview·Buy reprint rights for this chapterLoads all of the following IO modules with a single
use
statement: IO::Handle, IO::Seekable, IO::File, IO::Pipe, and IO::Socket.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO::File
- Content preview·Buy reprint rights for this chapterInherits from IO::Handle and IO::Seekable, extending them with methods specific to filehandles. Provides three such methods:new$fh = new ([ params ])DescriptionConstructor. Creates an IO::File object, passing any parameters to the method
open
. If the open fails, the object is destroyed. Otherwise, it is returned to the caller.new_tmpfile$fh = new_tmpfileDescriptionConstructor. Creates an IO::File object opened for read/write on a newly created temporary file. If the system permits, the temporary file is anonymous; if the temporary file cannot be created or opened, the object is destroyed. Otherwise, it is returned to the caller.open$fh ->open(filename[, mode[, perms]])DescriptionOpens the newly-created filehandle. Accepts one, two, or three parameters. With one parameter, it acts as a front-end for Perl's built-inopen
function. With two parameters, the first parameter is a filename and the second is the open mode, optionally followed by a third parameter, the file permission value.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO::Handle
- Content preview·Buy reprint rights for this chapterThe base class for all other IO handle classes. Its main purpose is for the other IO classes to inherit from it; programs should not create IO::Handle objects directly. Provides the following methods:newnewDescriptionConstructor. Creates a new IO::Handle object.new_from_fdnew_from_fd (fd, mode)DescriptionConstructor. Like
new
, creates an IO::Handle object. It requires two parameters, which are passed to the methodfdopen
; if thefdopen
fails, the object is destroyed. Otherwise, it is returned to the caller.clearerr$fh ->clearerrDescriptionClears the given handle's error indicator.error$fh ->errorDescriptionReturns a true value if the given handle has experienced any errors since it was opened or since the last call toclearerr
.fdopen$fh ->fdopen ( fd, mode )DescriptionAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO::Pipe
- Content preview·Buy reprint rights for this chapterProvides an interface for creating pipes between processes.new$pipe = new IO::Pipe([ readfh, writefh ])DescriptionConstructor. Creates an IO::Pipe object, which is a reference to a newly created symbol. The two optional arguments should be objects blessed into IO::Handle or one of its subclasses. These objects are used for the system call to
pipe
. With no arguments, the methodhandles
is called on the new IO::Pipe object.reader$pipe ->reader([ args ])DescriptionObject is reblessed into a subclass of IO::Handle and becomes a handle at the reading end of the pipe. If there are any args, thenfork
is called and the arguments are passed toexec
.writer$pipe ->writer([ args ])DescriptionThe object is reblessed into a subclass of IO::Handle and becomes a handle at the writing end of the pipe. If there are any args, thenfork
is called and the arguments are passed toexec
.handles$pipe ->handles()Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO::Seekable
- Content preview·Buy reprint rights for this chapterIntended to be inherited by other IO::Handle-based objects to provide methods that allow seeking of the file descriptors. Has no constructor.
use IO::Seekable; package IO::XXX; @ISA = qw(IO::Seekable);
Provides two methods:seek$fh ->seek( offset, whence )DescriptionFront-end for the corresponding built-inseek
function, which sets a filehandle's position in the file. Takes the following arguments:- offset
-
The offset where you want to set the position.
- whence
-
The position in the file that the offset is relative to. Possible values are:
0
for the beginning of the file,1
for the current position, or2
for end of file. May also be expressed as the following constants, which are exported:
tell$fh->tell()DescriptionFront-end for the corresponding built-intell
function, which returns the current file position in bytes (starting from 0).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO::Select
- Content preview·Buy reprint rights for this chapterImplements an object-oriented approach to the system
select
function call. Allows the user to see what IO handles are ready for reading, writing, or have an error condition pending.newnew $s = IO::Select->new([ handles ])DescriptionConstructor. Creates a new object and optionally initializes it with a set of handles.add$s ->add( handles )DescriptionAdds list of handles to the IO::Select object, to be returned when an event occurs. IO::Select keeps the list of handles in a cache, which is indexed by the handle's file number. Each handle can be an IO::Handle object, an integer, or a reference to an array, where the first element is an IO::Handle object or an integer.bits$s ->bits()DescriptionReturns the bit string that is suitable for use as argument to the coreselect
call.can_read$s ->can_read([ timeout ])DescriptionReturns array of handles that are ready for reading.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IO::Socket
- Content preview·Buy reprint rights for this chapterProvides an object interface to creating and using sockets. It is built on the IO::Handle interface and inherits all the methods defined by IO::Handle.IO::Socket defines methods for only those operations that are common to all types of socket. IO::Socket exports all functions (and constants) defined by Socket. See Chapter 13, for detailed information.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IPC::Msg
- Content preview·Buy reprint rights for this chapterSystem V Msg IPC object class. Uses constants defined in IPC::SysV.new$msg = new IPC::Msg( key, flags )DescriptionCreates a new message queue associated with key and uses flags to set the permissions. Creates the new message queue if the following are true:
-
key is equal to IPC_PRIVATE.
-
key doesn't already have an associated message queue and
FLAGS & IPC_CREAT
is true.
id$msg ->idDescriptionReturns the system identifier for the message queue.rcv$msg ->rcv( buf, len [, type [, flags ]])DescriptionReads a message from the queue, returning the type of the message.remove$msg ->removeDescriptionAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- IPC::Open2
- Content preview·Buy reprint rights for this chapterOpens a child process that allows two-way communication between your program and the child. Returns the process ID of the child process or reports a fatal error on failure. Exports one function:open2open2 (\*rdr, \*wtr, cmd_with_args)DescriptionForks a child process to execute the specified command. Takes the following arguments:
- \*rdr
-
Represents a read filehandle that your program can use to read from the command $cmd's standard output. Can be a FileHandle object or a reference to a typeglob.
- \*wtr
-
Represents a write filehandle that your program can use to write to the command $cmd's standard input. Can be a FileHandle object or a reference to a typeglob.
- cmd_with_arguments
-
The command to be executed by the child process, and its arguments. Can be specified two ways:
$cmd_with_args $cmd, "arg1", "arg2", ...
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - IPC::Open3
- Content preview·Buy reprint rights for this chapterIPC::Open3 works like IPC::Open2.
use IPC::Open3; $pid = open3($wtr, $rdr, $err, $cmd_with_args); $pid = open3($wtr, $rdr, $err, $cmd, "arg1", "arg2", ...);
The following differences apply:-
The first two arguments (
$wtr
and$rdr
) are passed in the opposite order. -
A third filehandle can be passed, for standard error. If this argument is given as
"carview.php?tsp="
, then STDERR and STDOUT for$cmd
are on the same filehandle. -
If
$wtr
begins with<
, then the leading<
is stripped from the name and the remainder is assumed to be a regular filehandle for an open file, rather than a reference to a typeglob.open3
opens this file as STDIN for$cmd
and closes it in the parent. Likewise, if$rdr
or$err
begins with>
, then$cmd
directs STDOUT or STDERR directly to that file rather than to the parent.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- IPC::Semaphore
- Content preview·Buy reprint rights for this chapterSystem V Semaphore IPC object class. Uses constants defined in IPC::SysV.new$sem = new IPC::Semaphore( key, nsems, flags )DescriptionCreates a new semaphore set associated with key and containing nsems semaphores. Uses flags to set the permissions. Creates the new set if the following are true:
-
key is equal to IPC_PRIVATE.
-
key doesn't already have an associated semaphore identifier and
FLAGS & IPC_CREAT
is true.
getall$sem ->getallDescriptionReturns the values of the semaphore set as an array.getncnt$sem ->getncnt( sem )DescriptionReturns the number of processes waiting for the semaphore sem to become greater than its current value.getpid$sem ->getpid( sem )Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- IPC::SysV
- Content preview·Buy reprint rights for this chapterDefines and conditionally exports all the constants defined in your system include files that are needed by the System V IPC calls.ftokftok (path, id)DescriptionReturns a key based on path and id for use by
msgget
,semget
, andshmget
.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - less
- Content preview·Buy reprint rights for this chapterPragma, currently unimplemented, that may someday be a compiler directive to make certain trade-offs, such as:
use less 'memory';
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - lib
- Content preview·Buy reprint rights for this chapterPermits adding additional directories to Perl's default search path at compile time. The directories are added at the front of the search path.
use lib list;
adds the directories specified in list to@INC
.For each directory $dir in list,lib
looks for an architecture-specific subdirectory that has an auto subdirectory under it-that is, it looks for $dir/$archname/auto. If it finds that directory, then $dir/$archname is also added to the front of@INC
, preceding $dir.Normally, you should only add directories to@INC
. However, you can also delete directories. The statement:no lib list
deletes the first instance of each named directory from@INC
. To delete all instances of all the specified names from@INC
, specify:ALL
as the first parameter of list.As with adding directories,lib
checks for a directory called $dir/$archname/auto and deletes the $dir/$archname directory from@INC
. You can restore@INC
to its original value with:@INC = @lib::ORIG_INC;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - locale
- Content preview·Buy reprint rights for this chapterPragma that tells the compiler to disable (or enable) the use of POSIX locales for built-in operations (LC_CTYPE for regular expressions and LC_COLLATE for string comparison). Each
no locale
oruse locale
affects statements to the end of the enclosing block.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Math::BigFloat
- Content preview·Buy reprint rights for this chapterProvides methods that permit use of floating-point numbers of arbitrary length. The following apply to all methods, except as noted:
-
The object $f remains unchanged.
-
All methods except
fcmp
return a number string (nstr) of the form/[+-]\d+E[+-]\d+/
, with embedded whitespace ignored. -
A return value of
NaN
indicates either that an input parameter was "Not a Number" or that an illegal operation was attempted. -
A similar default scale value is computed for square roots.
new$f = Math::BigFloat->new( string )DescriptionCreates a new object, $f.fabs$f ->fabs()DescriptionReturns absolute value of $f.fadd$f ->fadd( nstr )DescriptionReturns sum of nstr and $f.fcmp$f ->fcmp( nstr ).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Math::BigInt
- Content preview·Buy reprint rights for this chapterAllows use of arbitrary length integers, where the following apply to all methods, except as noted:
-
The object $i remains unchanged.
-
Big integer strings (bints) have the form
/^\s*[+-]?[\d\s]+$/
. -
All methods except
bcmp
return a big integer string or strings. -
Embedded whitespace is ignored.
-
Output values are always in the canonical form:
/^[+-]\d+$/
. -
The return value
NaN
results when an input argument is not a number, or when a divide by zero is attempted.
new$i = Math::BigInt->new( string )DescriptionCreates a new object, $i.babs$i ->babsDescriptionReturns absolute value of $i.badd$i ->badd( bint )DescriptionReturns sum of bint and $i.bcmp$iAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Math::Complex
- Content preview·Buy reprint rights for this chapterProvides support for complex numbers, including a full set of mathematical functions; permits creation and manipulation of complex numbers. Numerous overload and other operations are provided for working with complex numbers. See the documentation for the module for the complete list and also for a discussion of complex numbers. The following methods are provided:emake$z = Math::Complex->emake( args )cplxe $z = cplxe(args)DescriptionCreates a complex number using the polar form.display_formatdisplay_format ([format])DescriptionWhen called as a method, sets display format for current object. If format is not specified, returns the current setting. Possible settings are:
-
c
-
Cartesian format
-
p
-
Polar format
When called as a function, overrides the default display format, which is Cartesian.make$z = Math::Complex->make(Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Math::Trig
- Content preview·Buy reprint rights for this chapterDefines many trigonometric functions not defined by the core Perl, plus the constant pi and some additional functions for converting angles. For example:
use Math::Trig; $x = tan(0.9); $halfpi = pi/2;
The following functions are defined. A slash (/
) between two functions means the values are aliases.-
acsc/acosec
,asec
,acot/acotan
-
Arcus cofunctions of sine, cosine, and tangent
-
acsch/acosech
,asech
,acoth/acotanh
-
Arcus cofunctions of hyperbolic sine, cosine, and tangent
-
asin
,acos
,atan
-
Arcus (inverse) functions of sine, cosine, and tangent
-
asinh
,acosh
,atanh
-
Arcus functions of hyperbolic sine, cosine, and tangent
-
atan2(y, x)
-
Principal value of arc tangent of y/x
-
csc/cosec
,sec
,cot/cotan
-
Cofunctions of sine, cosine, and tangent
-
csch/cosech
,sech
,coth/cotanh
-
Cofunctions of hyperbolic sine, cosine, and tangent
-
deg2rad
-
Degrees to radians
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- NDBM_File
- Content preview·Buy reprint rights for this chapterProvides Perl programs with tied access to NDBM database files. See Perl's built-in
tie
function and the DB_File module.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::hostent
- Content preview·Buy reprint rights for this chapterOverrides the core
gethostbyname
andgethostbyaddr
functions with object-oriented versions that return Net::hostent objects. The objects have methods that return the fields of the same name from the hostent structure in netdb.h:Field Description addr
Address of host, for backwards compatibilityaddr_list
List of addresses returned from name serveraddrtype
Host address type aliases
List of aliases length
Length of address name
Name of host You can access the structure fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and then accessing them by prependingh_
to the field name:$host_obj->name() $h_name
Net::hostent exports the following:gethostgethost (host)DescriptionFront-end forgethostbyaddr
andgethostbyname
. If host is numeric, callsgethostbyaddr
, otherwise callsgethostbyname
.gethostbyaddrgethostbyaddr (addr, addrtype)DescriptionReturns information about the host with address addr of type addrtype.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::netent
- Content preview·Buy reprint rights for this chapterReturns information for a network. Overrides the core
getnetbyname
andgetnetbyaddr
functions with object-oriented versions that return Net::netent objects. The objects have methods that return the fields of the same name from the netent structure in netdb.h:Field Description addrtype
Net address type aliases
Array of aliases name
Name of net net
Network number You can access the structure fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and then accessing them by prependingn_
to the field name:$net_obj->name() $n_name
Net::netent exports the following:getnetgetnet (net)DescriptionFront-end forgetnetbyaddr
andgetnetbyname
. If net is numeric, callsgetnetbyaddr
, otherwise callsgetnetbyname
.getnetbyaddrgetnetbyaddr (addr, addrtype)DescriptionReturns information about the net with address addr of type addrtype.getnetbynamegetnetbyname (netname)DescriptionReturns information about the net with name netname.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::Ping
- Content preview·Buy reprint rights for this chapterProvides methods to create ping objects and test the reachability of remote hosts on the network. After the object has been created, a variable number of hosts can be pinged multiple times before closing the connection. The methods are:new$p = Net::Ping->new([ proto [, def_timeout [, bytes ]]])DescriptionCreates a new ping object. All arguments are optional. Takes the following arguments:
- proto
-
The protocol to use when doing a ping. Default is
udp
. The possible protocols are: - def_timeout
-
Default timeout in seconds to be used if timeout not passed to the
ping
method. Must be greater than zero; defaults to 5 seconds. - bytes
-
Number of bytes included in the ping packet sent to the remote host. Ignored if protocol is tcp. Default is 1 if protocol is udp, otherwise 0. These are also the minimum number of bytes; the maximum is 1024.
close$p ->close()Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::protoent
- Content preview·Buy reprint rights for this chapterReturns information for an Internet protocol. Overrides the core
getprotoent
,getprotobyname
, andgetprotobynumber
functions with object-oriented versions that return Net::protoent objects. The functions take a default second argument oftcp
. The objects have methods that return the fields of the same name from the protoent structure in netdb.h:Field Description aliases
List of aliases name
Name of host proto
Protocol You can access the structure fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and then accessing them by prependingp_
to the field name:$proto_obj->name() $p_name
getprotogetproto (protocol)DescriptionFront-end forgetprotobynumber
andgetprotobyname
. If protocol is numeric, callsgetprotobynumber
, otherwise callsgetprotobyname
.getprotoentgetprotoent (protocol)DescriptionFront-end forgetprotobynumber
andgetprotobyname
. If protocol is numeric, callsgetprotobynumber
, otherwise callsgetprotobyname
.getprotobynamegetprotobyname (addr, addrtype)DescriptionReturns information about the host with addressAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::servent
- Content preview·Buy reprint rights for this chapterReturns information for an Internet service. Overrides the core
getservent
,getservbyname
, andgetservbyport
functions, replacing them with versions that return Net::servent objects. The functions take a default second argument oftcp
. The objects have methods that return the fields of the same name from the servent structure in netdb.h:Field Description aliases
List of aliases name
Name of service port
Port proto
Protocol to use You can access the structure fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and then accessing them by prependings_
to the field name:$serv_obj->name() $s_name
getservgetserv(service)DescriptionFront-end forgetservbyport
andgetservbyname
. If service is numeric, callsgetservbyport
, otherwise callsgetservbyname
.getservbynamegetservbyname(name)DescriptionReturns information for the Internet service with protocol name name.getservbyportgetservbyport(port)DescriptionReturns information for the Internet service with port numberAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - O
- Content preview·Buy reprint rights for this chapterGeneric interface to the Perl compiler backends. Also see the B module.
perl -MO=backend[,options] perlscript
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ODBM_File
- Content preview·Buy reprint rights for this chapterProvides Perl programs with tied access to ODBM database files. See Perl's built-in
tie
function and the DB_File module.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Opcode
- Content preview·Buy reprint rights for this chapterPermits defining an operator mask so that any code containing a masked opcode will not compile or execute when Perl next compiles any code. Not usually used directly; for examples of Opcode's use, see the
ops
pragma and the Safe module.Valid opcodes are listed in the arrayop_name
in the file opcode.h. Many Opcode functions and methods take lists of operators, which are composed of elements. Each element can be a:- name (opname) or negated name
-
Name of operator, usually lowercase. Prefixing the name with an exclamation mark (
!
) removes it from the accumulated set of operations. - set (opset)
-
Operator set. Binary string holding a set of zero or more operators.
- tag name (optag) or negated tag
-
Operator tag name; refers to groups (or sets) of operators. Begins with a colon (
:
). Negated by prefixing with an exclamation mark (!
). Several optags are predefined, including the following. See the manpage for the Opcode module for the opcodes included in each tag.:base_core :base_io :base_loop :base_math :base_mem :base_orig :browse :dangerous :default :filesys_open :filesys_read :filesys_write :others :ownprocess :still_to_be_decided :subprocess :sys_db
All the following functions can be exported:define_optagdefine_optag (optag, opset)DescriptionAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - ops
- Content preview·Buy reprint rights for this chapterPragma that disables unsafe opcodes during compilation. Can also be used to specify opcodes to be disabled. Generally used with the -M option on the command line:
perl -Mops=:default ... # only allow reasonably safe operations perl -M-ops=system ... # disable system opcode
See the Opcode module for more information.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - overload
- Content preview·Buy reprint rights for this chapterLets you substitute class methods or your own subroutines for standard Perl operators. For example, the code:
package Number; use overload "+" => \add, "*=" => "muas";
declares functionadd
for addition and methodmuas
in the Number class (or one of its base classes) for the assignment form*=
of multiplication.Arguments touse overload
are key/value pairs, where the key is the operation being overloaded, and the value is the function or method that is to be substituted. Legal values are values permitted inside a&{ … }
call, so a subroutine name, a subroutine reference, or an anonymous subroutine are all legal. Legal keys (overloadable operations) are:Type Operations Arithmetic + - * / % ** << >> x .
+= -= *= /= %= **= <<= >>= x= .=
Comparison < <= > >= == != <=>
lt le gt ge eq ne cmp
Bit and unary % ^ | neg ! ~
Increment, decrement ++ -
Transcendental atan2 cos sin exp abs log sqrt
Boolean, string, numeric conversionbool
"carview.php?tsp="
0+
Special nomethod fallback =
The functions specified with theuse overload
directive are typically called with three arguments. If the corresponding operation is binary, then the first two arguments are the two arguments of the operation. However, the first argument should always be an object in the package, so in some cases, the order of the arguments will be interchanged before the method is called. The third argument provides information on the order and can have these values:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Pod::Functions
- Content preview·Buy reprint rights for this chapterUsed internally by Pod::Html for use in converting from pod to HTML.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Pod::Html
- Content preview·Buy reprint rights for this chapterConverts files from pod to HTML format. Not generally used directly, but via the pod2html script (see Chapter 4), which is included in the standard distribution.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Pod::Text
- Content preview·Buy reprint rights for this chapterConverts files from pod format to formatted ASCII text. Not generally used directly, but via the pod2text script (see Chapter 4). Termcap is optionally supported for boldface and underlining and can be enabled with:
$Pod::Text::termcap=1
Otherwise, backspaces are used to simulate bold and underlined text. Exports one function:pod2textpod2text (filename[, filehandle])DescriptionConverts from pod to text format. Takes the following arguments:- filename
-
File to convert, or
<&STDIN
to read from STDIN. - filehandle
-
Optional. Filehandle glob to which output should be sent (
*STDOUT
to write to STDOUT).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - POSIX
- Content preview·Buy reprint rights for this chapterProvides access to standard POSIX 1003.1 identifiers: functions, classes, and constants. Can be
use
d to import one or multiple symbols:use POSIX; # import all symbols use POSIX qw(setsid); # import one symbol use POSIX qw(:errno_h :fcntl_h); # import sets of symbols
Functions listed as C-specific are not implemented._exit Identical to C function _exit(2)
abort Identical to C function abort(3)
abs Identical to Perl's abs
functionaccess Determines accessibility of a file; returnsundef
on failureacos Identical to C functionacos(3)
alarm Identical to Perl'salarm
functionasctime Identical to C functionasctime(3)
asin Identical to C functionasin(3)
assert Similar to C macroassert(3)
atan Identical to C functionatan(3)
atan2 Identical to Perl'satan2
functionAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - re
- Content preview·Buy reprint rights for this chapterPragma that lets you alter the behavior of regular expressions. Permits the following alterations:
-
use re 'debug'
-
Causes Perl to produce debugging messages when compiling and at run time when using regular expressions. See the re manpage and the section on "Debugging regular expressions" in the perldebug manpage for details.
-
use re 'eval'
-
Permits a regular expression to contain
(?{…})
zero-width assertion even if the regular expression contains variable interpolation, which normally isn't permitted for security reasons. The pragma is ignored if the regular expression comes from tainted data. -
use re 'taint'
-
When a tainted string is the target of a regular expression, causes the regular expression memories (or the values returned by the
m//
operator in list context) to be tainted.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Safe
- Content preview·Buy reprint rights for this chapterCreates compartments for evaluating untrusted Perl code. Each compartment has an associated operator mask for excluding particular Perl operators from the compartment. See the Opcode module for more information on operators and operator masks. The default mask is applied during compilation to prevent all operations that give access to the system. Safe provides the following methods:new$cpt = new Safe [( namespace, mask )]DescriptionConstructor. Creates a new compartment. Takes the following arguments:
- namespace
-
Optional. Root namespace to use for the compartment. Default is
"Safe::Root0"
, which auto-increments for each new compartment. - mask
-
Optional. Operator mask to use; defaults to a restrictive set.
mask$cpt ->mask ([ mask ])DescriptionSets operator mask for the compartment if mask is specified, otherwise it gets the current mask.rdoAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - SDBM_File
- Content preview·Buy reprint rights for this chapterProvides Perl programs with tied access to SDBM database files. See Perl's built-in
tie
function and the DB_File module.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Search::Dict
- Content preview·Buy reprint rights for this chapterSearches for a key in an ordered text file and sets the file position. Exports one function:looklook *fh, key, dict, foldDescriptionPerforms string search and sets the position in filehandle fh to the first line with a key equal to or greater than key. Returns the new file position, or -1 in case of error. Takes the following arguments:
- fh
-
Filehandle of the dictionary file.
- key
-
Key to search for.
- dict
-
If true, searches in dictionary order, considering only word characters and whitespace.
- fold
-
If true, ignore case.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - SelectSaver
- Content preview·Buy reprint rights for this chapterProvides a way to save and restore filehandles so you can temporarily use a different filehandle.new$saver = new SelectSaver[( fh )]DescriptionConstructor. Creates a new SelectSaver object, $saver, which saves the current filehandle. The optional parameter fh is the filehandle that is to temporarily replace the current filehandle. If fh is present, the current filehandle is saved in $saver and the new one becomes the current filehandle. With no parameter, the current filehandle is saved in the object $saver, and it also remains current.You can use the newly selected filehandle within the current block. When you exit the block, the previous filehandle is again made the current one, and the SelectSaver object in which it was stored is destroyed.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - SelfLoader
- Content preview·Buy reprint rights for this chapterUsed when you want to include functions in your program, but you want to load them only if necessary. Functions to be self-loaded are placed after the line:
__DATA__
in your program. When the code is compiled, compilation stops at the__DATA__
token. The SelfLoader exports theAUTOLOAD
subroutine to the package; this subroutine loads the subroutines after__DATA__
when they arerequire
d.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Shell
- Content preview·Buy reprint rights for this chapterAllows you to invoke Unix shell utilities as if they were Perl subroutines. Arguments (including switches) are passed to the utilities as strings:
use Shell qw(date cp ps); # list shell commands you want to use $date = date(); # put the output of the date(1) command into $date cp("-p" "/etc/passwd", "/tmp/passwd"); # copy password file to a tmp file print ps("-ww"); # print the results of a "ps -ww" command
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - sigtrap
- Content preview·Buy reprint rights for this chapterPragma to enable simple signal handling. Provides two signal handlers that can be installed, or you can install your own handler; also provides options to specify which signals to trap. Ignores requests to trap signals not used in your system's architecture.
use sigtrap; # initialize default signal handlers use sigtrap qw(die normal-signals); use sigtrap 'handler' => \handlername, 'normal-signals'; use sigtrap qw(handler handlername normal-signals stack-trace error-signals);
Used to specify which handler is to be installed and used for signals installed after the handler:-
die
-
Installs handler that
die
s with a message indicating what signal was trapped. -
handler
handlername -
Installs your handler handlername.
-
stack-trace
-
Default signal handler. Outputs stack trace to STDERR and tries to dump core.
You can specify your own list of options:use sigtrap qw(BUS SEGV PIPE ABRT);
or use one of the following built-in option lists:-
error-signals
-
Signals that indicate a serious problem: ABRT, BUS, EMT, FPE, ILL, QUIT, SEGV, SYS, and TRAP.
-
normal-signals
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Socket
- Content preview·Buy reprint rights for this chapterTranslation of the C socket.h file that uses h2xs and your C compiler. See Chapter 13 for the details.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - strict
- Content preview·Buy reprint rights for this chapterPragma for doing strict error checking within the current block. Can be turned off by prefixing with
no
:use strict 'vars'; ... no strict 'vars';
Provides three kinds of restriction:-
strict 'refs'
-
Generates runtime error if you use any symbolic references.
-
strict 'subs'
-
Generates compile-time error if you use a bareword identifier that’s not a predeclared subroutine.
-
strict 'vars'
-
Generates compile-time error if you access a variable that wasn’t declared via
my
, isn’t fully qualified, or wasn’t imported.
use strict
by itself (with no import list) is the most restrictive, causing all possible restrictions to be imposed.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- subs
- Content preview·Buy reprint rights for this chapterPragma that predeclares subroutines whose names are given in a list:
use subs qw(sub[, ...]); sub $arg[, ...];
This lets you use the subroutines without parentheses even before they're defined, and lets you override built-in functions.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Symbol
- Content preview·Buy reprint rights for this chapterProvides functions for creating anonymous globs and qualifying variable names. Exports the following:gensymgensymDescriptionCreates an anonymous glob and returns a reference to it that can be used as a filehandle or directory handle.ungensymungensymDescriptionFor backward compatibility only; does nothing.qualifyqualify (symname[, pkg])DescriptionTurns unqualified symbol names into qualified variable names (e.g., turns
myvar
intoMyPackage::myvar
).qualify_to_refqualify_to_ref (symname[, pkg])DescriptionLikequalify
, but returns a glob ref that can be used even ifuse strict 'refs'
is in effect.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Sys::Hostname
- Content preview·Buy reprint rights for this chapterProvides one function,
hostname
, which attempts to get the system hostname by doing checks appropriate to the operating system. Removes nulls, returns, and newlines from the result, which it then caches.croak
s on failure.use Sys::Hostname; $host = hostname();
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Sys::Syslog
- Content preview·Buy reprint rights for this chapterInterfaces to Unix
syslog(3)
program. Requires the file syslog.ph, which must be created with h2ph by your system administrator. Provides the following four functions:closelogcloselogDescriptionCloses the log file.openlogopenlog ident, logopt, facilityDescriptionOpens the log file. Takes the following arguments:- ident
-
Prepended to every message.
- logopt
-
Logging options, containing one or more of:
- facility
-
Specifies the part of the system making the log entry.
setlogmasksetlogmask mask_priorityDescriptionSets log mask to mask_priority and returns the old mask.syslogAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Term::Cap
- Content preview·Buy reprint rights for this chapterProvides low-level functions to extract and use capabilities from a terminal capability (termcap) database. For general information about the use of this database, see the termcap(5) manpage. Provides the following functions:Tgetent$terminal = Tgetent Term::Cap { TERM => termtype, OSPEED=> ospeed }DescriptionActs as the constructor for Term::Cap. Extracts the termcap entry for terminal type termtype and returns a reference to a terminal object. The termcap entry itself is
$terminal->{TERMCAP}
. CallsCarp::croak
on failure. Takes the following arguments:-
TERM =>
termtype -
Terminal type. Defaults to the value of the environment variable TERM if termtype is false or undefined.
-
OSPEED =>
ospeed -
The terminal output bit rate, specified as either a POSIX termios/SYSV termio speed or an old BSD-style speed. You can use the POSIX module to get your terminal's output speed (in ospeed here).
Tgoto$terminal ->Tgoto('cm', col, row [, fh ])DescriptionProduces control string to move the cursor relative to the screen. Doesn't cache output strings, but doesAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Term::Complete
- Content preview·Buy reprint rights for this chapterProvides word completion on list of words in a specified array. Exports one function:CompleteComplete ('prompt_string', array)DescriptionSends string to the currently selected filehandle, reads the user's response, and returns the response. Takes the following arguments:
- prompt_string
-
The prompt for user input.
- array
-
The array of words against which the user's input is matched.
If any of the following characters are included in the user's response to prompt_string, they are treated as special characters:- TAB
-
Does word completion, matching what the user has typed so far against the list of strings in completion_list. On a unique match, outputs the rest of the matched string and waits for the user to press the return key. Otherwise, leaves partial input unchanged and sounds the bell.
- CTRL-D
-
Prints all possible completions of the user's partial input, or the entire completion list if the partial input string is null, and reissues the prompt string and the partial input. Redefine by setting the variable
$Term::Complete::complete
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Term::ReadLine
- Content preview·Buy reprint rights for this chapterFront-end to other ReadLine packages. Currently interfaces to Term-ReadLine, which is available on CPAN. Defines the variables
$IN
and$OUT
, which return the filehandles for input and output, respectively, orundef
if Readline input and output cannot be used for Perl. Provides the following methods:new$term = new Term::ReadLine 'name'DescriptionConstructor. Returns the handle for subsequent calls to other ReadLine methods. Argument name is the name of the application. Optionally can be followed by two arguments that are globs specifying input and output filehandles.addhistory$term ->addhistory( line )DescriptionAdds line to the input history.Features$term ->FeaturesDescriptionReturns a reference to a hash whose keys are features present in the current implementation and whose values are those assigned to each feature. Several optional features are used in the minimal interface: appname should be present if the first argument tonew
is recognized, and minline should be present ifMinLine
method is not a dummy. autohistory should be present if lines are put into history automatically (maybe subject to MinLine), and addhistory if theaddhistory
method is not a dummy.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Test
- Content preview·Buy reprint rights for this chapterProvides a framework for writing test scripts so you don't need to know the particular output that Test::Harness expects to see. Useful if you are writing modules and writing tests for those modules. Provides the following test types:
- Normal
-
Tests that are expected to succeed.
- Skip
-
Tests that need a platform-specific feature. They work like normal tests except that the first argument should evaluate to true if the required feature is not present.
- Todo
-
Tests that are designed for maintaining an executable todo list; the tests aren't expected to succeed.
Test also provides an onfail hook that can trigger additional diagnostics for failures at the end of the test run. To use onfail, pass it an array reference of hash references where each hash contains at least these fields: package, repetition, and result, as well as any expected value or diagnostic string.See the Test manpage for details and examples.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Test::Harness
- Content preview·Buy reprint rights for this chapterUsed by MakeMaker; runs Perl test scripts and prints some statistics. You can use the Test module to write test scripts without knowing the exact output Test::Harness expects. Exports one function:runtestsruntests (tests)DescriptionRuns all test scripts named in tests and checks standard output for the expected
ok
n strings. Prints performance statistics after all tests have been run.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Text::Abbrev
- Content preview·Buy reprint rights for this chapterGiven a list of strings, creates a hash of unambiguous abbreviations. Exports one function:abbrevabbrev (\%hashref, list)DescriptionTakes each string in list and constructs the hash referenced by \hashref. Each key is an unambiguous truncation of one of the strings, and the value is the full string (where unambiguous means that there is only one possible expansion that matches one of the strings in the list). For example, if list contains "file" and "find", then the key/value pairs created include:
fil => file file => file fin => find find => find
Both "f" and "fi" are ambiguous, since they start both words, and therefore they don't appear as keys.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Text::ParseWords
- Content preview·Buy reprint rights for this chapterParses lines of text and returns an array of words. Provides three functions:quotewordsquotewords (delim, keep, lines)DescriptionAccepts delimiter and list of lines and breaks the lines up at occurrences of the delimiter into a list of words. Exported by default. Takes the following arguments:
- delim
-
Delimiter, which can be a regular expression. Occurrences inside quotes are ignored.
- keep
-
Boolean. If false, quotes and single backslashes are removed from the list of words returned, and a double backslash is returned as a single backslash. If true, quotes and backslashes are retained.
- lines
-
The list of lines to be parsed.
old_shellwordsold_shellwords (lines)DescriptionSplits an array of lines into words. Exported on request. Same as the pre-Perl 5 program shellwords.pl.shellwordsshellwords (lines)Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Text::Soundex
- Content preview·Buy reprint rights for this chapterImplements the soundex algorithm, which hashes a word (in particular, a surname) into a compressed form that approximates the sound of the word when spoken by an English speaker.
use Text::Soundex; $code = soundex $string; # get soundex code for a string @codes = soundex @list; # get list of codes for list of strings
Returns the value of the variable$soundex_nocode
if there is no soundex code representation for a string.$soundex_nocode
is initially set toundef
, but can be reset to another value, e.g.:$soundex_nocode = 'Z000';
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Text::Tabs
- Content preview·Buy reprint rights for this chapterProvides subroutines that expand tabs into spaces and compress ("unexpand") spaces into tabs. The appearance of the text is unchanged. Defines the
tabstop
variable, which defines the number of spaces equivalent to a tab. Default is 8. Exports the following functions:expandexpand (text)DescriptionGiven an array of strings (text) containing tabs, replaces each tab character with the equivalent number of spaces.unexpandunexpand (text)DescriptionGive an array of strings (text), that may or may not contain tabs, replaces each $tabstop consecutive spaces with a tab character.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Text::Wrap
- Content preview·Buy reprint rights for this chapterWraps text into a paragraph. Defines the
$columns
variable, which specifies the output line length. Default is 76. Exported on request. Provides the following function:wrapwrap (init_str, other_str, text)DescriptionBreaks lines of array text at the word boundary closest to the size of a line. Prepends init_str to the first output line and other_str to subsequent lines, for indentation. Exported by default.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Thread
- Content preview·Buy reprint rights for this chapterProvides Perl multithreading support. Distributed as a beta feature with Perl 5.005 and runs only on versions of Perl that were built with thread support. Has the following functions and methods:new$t = new Thread \ &sub [, params ]DescriptionConstructor. Starts a new thread in the referenced subroutine, \sub, returning a thread object that represents the new thread. The optional parameter list is passed to the subroutine. Execution continues in both the new thread and the code.async$t = async { block };DescriptionCreates a new thread to execute the block that follows it. The block is treated as an anonymous subroutine (and therefore has a semicolon after the closing bracket). Returns a thread object.
async
isn't exported by default, so you can either specifyuse Thread qw(async);
or fully qualify the name (Thread::async
).cond_broadcastcond_broadcast varDescriptionLikecond_wait
, but unblocks all threads blocked in acond_wait
on the locked variable, not just one thread.cond_signalcond_signalAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Thread::Queue
- Content preview·Buy reprint rights for this chapterProvides a thread-safe queue. Any number of threads can add elements to the end of the queue or remove elements from the head.new$q = new Thread::QueueDescriptionCreates a new empty queue. Returns an object representing the queue.dequeue$q ->dequeueDescriptionRemoves and returns a scalar from the head of the queue. If the queue is empty,
dequeue
blocks the thread until another threadenqueue
s a scalar on the queue.dequeue_nb$q ->dequeue_nbDescriptionLikedequeue
but returnsundef
if the queue is empty, instead of blocking.enqueue$q ->enqueue listDescriptionAdds the list of scalars, list, to the end of the queue.pending$q ->pendingDescriptionReturns the number of items remaining in the queue.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Thread::Semaphore
- Content preview·Buy reprint rights for this chapterProvides a mechanism to regulate access to resources. Semaphores are more general than locks because they aren't tied to a particular scalar. They can have values other than zero or one, and they can be incremented or decremented by some specified number.new$sem = new Thread::Semaphore([ val ])DescriptionConstructor. Creates a new semaphore object, with an optional initial count of val, or
1
if val isn't specified.downdown [number]DescriptionDecrements the semaphore's count by the specified number, which defaults to1
. If the resulting count would be negative, blocks until the semaphore's count has been increased to be equal to or larger than the amount you want to decrease it.upup [number]DescriptionIncrements the semaphore's count by the specified number, which defaults to1
. If a thread is blocked waiting to decrement the count, and the increment brings the count high enough, the blocked thread is unblocked.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Thread::Signal
- Content preview·Buy reprint rights for this chapterStarts a special signal handler thread to reliably run signal handlers. All signals are handed to this thread, which runs the associated
$SIG{
signal}
handlers for them.use Thread::Signal; $SIG{HUP} = handler;
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Thread::Specific
- Content preview·Buy reprint rights for this chapterProvides thread-specific keys.key_create$k = key_create Thread::SpecificDescriptionConstructor. Creates a Thread::Specific key object.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Tie::Array, Tie::StdArray
- Content preview·Buy reprint rights for this chapterProvides methods for array-tying classes. See the perltie manpage for the functions needed for tying an array to a package. The basic Tie::Array package provides stub DELETE and EXTEND methods, and it implements PUSH, POP, SHIFT, UNSHIFT, SPLICE, and CLEAR in terms of basic FETCH, STORE, FETCHSIZE, and STORESIZE.Tie::StdArray inherits from Tie::Array and provides the methods needed for tied arrays that are implemented as blessed references to an "inner" Perl array. It causes tied arrays to behave like standard arrays, allowing for selective method overloading.See the perltie manpage for more detailed information and for examples. To write your own tied arrays, use the following required methods:TIEARRAYTIEARRAY classname, listDescriptionConstructor. This method is invoked by the command
tie
@array, classname. Associates an array instance with the specified class. list represents additional arguments needed to complete the association. Should return an object of a class that provides the remaining methods.CLEARCLEAR thisDescriptionClears all values from the tied array associated with object this.DESTROYDESTROY thisDescriptionAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Tie::Handle
- Content preview·Buy reprint rights for this chapterProvides skeletal methods for handle-tying classes. Tie::Handle provides a
new
method as backup in case a class has noTIEHANDLE
method. See the perltie manpage for more detailed information and for examples. To write your own tied-handle classes, use the following methods:TIEHANDLETIEHANDLE classname, listDescriptionConstructor. This method is invoked by the commandtie
*glob, classname. Associates new glob instance with class classname. list represents any additional arguments needed to complete the association.DESTROYDESTROY thisDescriptionFrees storage associated with the tied handle this. Permits class to take some action when an instance is destroyed. Rarely needed.GETCGETC thisDescriptionGets one character from tied handle this.PRINTPRINT this, listDescriptionPrints the values in list.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Tie::Hash, Tie::StdHash
- Content preview·Buy reprint rights for this chapterProvides skeletal methods for hash-tying classes. Tie::Hash provides a
new
method, as well as the methodsTIEHASH
,EXISTS
, andCLEAR
. The Tie::StdHash package inherits from Tie::Hash and causes tied hashes to behave like standard hashes, allowing for selective method overloading. It provides most methods required for hashes. Thenew
method is provided as backup in case a class has noTIEHASH
method.To write your own tied hashes, the methods listed here are required. See the perltie manpage for more detailed information and for examples.TIEHASHTIEHASH ClassName, listDescriptionConstructor. Associates a new hash instance with class ClassName. list is a list of additional arguments needed to complete the association.tie %hash, ClassName, list
CLEARCLEAR thisDescriptionClears all values from tied hash this.DELETEDELETE this, keyDescriptionDeletes key from tied hash this.EXISTSEXISTS this, keyAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Tie::RefHash
- Content preview·Buy reprint rights for this chapterProvides the ability to use references as hash keys after you've tied a hash variable to the module:
use Tie::RefHash; tie hashvariable, 'Tie::RefHash', list; untie hashvariable;
Uses the TIEHASH interface and provides the same methods.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Tie::Scalar, Tie::StdScalar
- Content preview·Buy reprint rights for this chapterProvides some skeletal methods for scalar-tying classes. The basic Tie::Scalar package provides a
new
method, as well as methodsTIESCALAR
,FETCH
, andSTORE
. The Tie::StdScalar package inherits from Tie::Scalar and causes scalars tied to it to behave like the built-in scalars, allowing for selective overloading of methods. Thenew
method is provided as backup in case a class has noTIESCALAR
method.To write your own tied hashes, the methods listed here are required. See the perltie manpage for more detailed information and for examples.TIESCALARTIESCALAR ClassName, listDescriptionConstructor. Associates new scalar instance with class ClassName. list represents any additional arguments needed to complete the association.tie $scalar, ClassName, list
DESTROYDESTROY thisDescriptionFrees storage associated with the tied scalar referenced by this. Permits a class to perform specific actions when an instance is destroyed. Rarely needed.FETCHFETCH thisDescriptionRetrieves value of the tied scalar referenced by this.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Tie::SubstrHash
- Content preview·Buy reprint rights for this chapterProvides a hash-table-like interface to a fixed-sized array that has a constant key size and record size.
require Tie::SubstrHash; tie %myhash, "Tie::SubstrHash", key_len, value_len, table_size;
To tie a new hash to this package, specify the following:- key_len
-
Length of each key
- value_len
-
Length of each value
- table_size
-
Size of the table given as the number of key/value pairs
An attempt to store a key/value pair where either the key or the value is the wrong length, or where the resulting table would be greater than table_size, results in a fatal error.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Time::gmtime
- Content preview·Buy reprint rights for this chapterReplaces Perl's core
gmtime
function with a version that returns Time::tm objects. Exports two functions:gmtime$gm = gmtime()DescriptionOverrides the coregmtime
function. The Time::tm object returned has methods with the same names as the structure fields they return. That is, to return the fieldmon
, use themon
method:use Time::gmtime; $gm = gmtime(); print $gm->mon;
The field names (and therefore the method names) are the same as the names of the fields in the tm structure in the C file time.h:sec
,min
,hour
,mday
,mon
,year
,wday
,yday
, andisdst
. You can access the fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependingtm_
to the method name (for example,$tm_mon
).gmctime$gmc = gmctime()DescriptionOverrides the coregmtime
function in scalar context; returns a string with the date and time:use Time::gmtime; $gmc = gmctime(); print $gmc;
Then the output of theprint
command looks like:Thu Apr 9 18:15:06 1998
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Time::Local
- Content preview·Buy reprint rights for this chapterProvides routines that take the time and return the number of seconds elapsed between January 1, 1970 and the specified time. The arguments are defined like the corresponding arguments returned by Perl's
gmtime
andlocaltime
functions and the results agree with the results of those functions. Exports two functions; both return -1 if the integer limit is hit. On most machines this applies to dates after January 1, 2038.timegm$time = timegm( sec, min, hours, mday, mon, year )DescriptionConverts from Greenwich time.timelocal$time = timelocal( sec, min, hours, mday, mon, year )DescriptionConverts from local time.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Time::localtime
- Content preview·Buy reprint rights for this chapterReplaces Perl's core
localtime
function with a version that returns Time::tm objects. Exports two functions:localtime$lt = localtime()DescriptionOverrides the corelocaltime
function. The Time::tm object returned has methods with the same names as the structure fields they return. That is, to return the field mon, use themon
method:use Time::localtime; $lt = localtime(); print $lt->mon;
The field names (and therefore the method names) are the same as the names of the fields in the tm structure in the C file time.h:sec
,min
,hour
,mday
,mon
,year
,wday
,yday
, andisdst
. You can access the fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependingtm_
to the method name (for example,$tm_mon
).ctime$ct = ctime()DescriptionOverrides the corelocaltime
function in scalar context; returns a string with the date and time:use Time::gmtime; $ct = ctime(); print $ct
Then the output of theprint
command looks like:Thu Apr 9 16:50:10 1998
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Time::tm
- Content preview·Buy reprint rights for this chapterUsed internally by Time::localtime and Time::gmtime. Don't use it directly. Creates addressable Time::tm struct object.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - UNIVERSAL
- Content preview·Buy reprint rights for this chapterBase class; all blessed references inherit from it.
$sub = $obj->can('print'); $yes = UNIVERSAL::isa($ref, "HASH");
Provides the following methods:can$sub = $obj ->can( method )DescriptionChecks if object $obj has a method method. If so, returns a reference to the subroutine, otherwise returnsundef
. Can be called as either a static or object method call, or as a subroutine:$ref = UNIVERSAL::can(val, method)
Returns a reference to the subroutine if val is a blessed reference with a method method, andundef
if val is not blessed or does not have method.isa$io = $fd ->isa( type )DescriptionReturns true if the reference is blessed into package type or inherits from that package. Can be called as a static or object method call, or as a subroutine:UNIVERSAL::isa(val, type)
Returns true if the first argument is a reference and either of the following is true:-
val is a blessed reference and is blessed into package type or inherits from package type
-
val is a reference to a type of Perl variable (e.g., '
HASH
')
VERSIONAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- User::grent
- Content preview·Buy reprint rights for this chapterOverrides core
getgrent
,getgruid
, andgetgrnam
functions with versions that return User::grent objects. The object returned has methods with the same names as the structure fields they return. That is, to return the field name, use thename
method:use User::grent; $gr = getgrgid(0) or die "No group zero"; if ( $gr->name eq 'wheel' && @{$gr->members} > 1 ) { print "gid zero name wheel, with other members"; }
The field names (and therefore the method names) are the same as the names of the fields in the group structure from the C file grp.h: name, passwd, gid, and members (not mem). The first three return scalars, the last an array reference. You can access the fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependinggr_
to the method name (for example,gr_name
).Exports four functions:getgr$gr ->getgr( arg )DescriptionFront-end that forwards a numeric arg togetgrid
and other args togetgrname
.getgrent$gr = getgrent()DescriptionSuccessive calls togetgrent
return objects representing successive entries from the group file.getgrgid$gr = getgrgid( gid )DescriptionAccesses the group file by group idAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - User::pwent
- Content preview·Buy reprint rights for this chapterOverrides core
getpwent
,getpwuid
, andgetpwnam
functions with versions that return User::pwent objects. The object returned has methods with the same names as the structure fields they return. That is, to return the field name, use thename
method:use User::pwent; $pw = getpwnam('daemon') or die "No daemon user"; if ( $pw->uid == 1 && $pw->dir =~ m#^/(bin|tmp)?$# ) { print "gid 1 on root dir"; }
The field names (and therefore the method names) are the same as the names of the fields in the passwd structure from the C file pwd.h: name, passwd, uid, gid, quota, comment, gecos, dir, and shell. You can access the fields either with the methods or by importing the fields into your namespace with the :FIELDS import tag and prependingpw_
to the method name (for example,pw_name
).Exports four functions:getpw$pw ->getpw( arg )DescriptionFront-end that forwards a numeric arg togetpwuid
and other args togetpwnam
.getpwent$pw ->getpwent()DescriptionSuccessive calls togetpwent
return objects representing successive entries from the password table.getpwnam$pw ->getpwnam( name )DescriptionAccesses the password table by user's name.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - vars
- Content preview·Buy reprint rights for this chapterPragma that, given a list of variable names, predeclares all variables in the list, making sure they are available to routines whose loading is delayed (e.g., routines that are loaded by the AutoLoader or SelfLoader). This allows you to use the variables under
use strict
. Thevars
pragma also disables warnings about typographical errors.use vars qw($var1 @var2 %var3);
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - vmsish
- Content preview·Buy reprint rights for this chapterPragma that currently supports three VMS-specific language features:
- status
-
Makes
$?
andsystem
return VMS status values instead of emulating POSIX. - exit
-
Makes
exit
take a VMS status value instead of assuming thatexit 1
is an error. - time
-
Makes all times relative to the local time zone.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 9: CGI Overview
- Content preview·Buy reprint rights for this chapterPerl is the most commonly used language for CGI programming on the World Wide Web. The Common Gateway Interface (CGI) is an essential tool for creating and managing comprehensive web sites. With CGI, you can write scripts that create interactive, user-driven applications.CGI allows the web server to communicate with other programs that are running on the same machine. For example, with CGI, the web server can invoke an external program, while passing user-specific data to the program (such as what host the user is connecting from, or input the user has supplied through an HTML form). The program then processes that data, and the server passes the program's response back to the web browser.Rather than limiting the Web to documents written ahead of time, CGI enables web pages to be created on the fly, based upon the input of users. You can use CGI scripts to create a wide range of applications, from surveys to search tools, from Internet service gateways to quizzes and games. You can increment the number of users who access a document or let them sign an electronic guestbook. You can provide users with all types of information, collect their comments, and respond to them.For Perl programmers, there are two approaches you can take to CGI. They are:
-
Programs that handle all CGI interaction directly, without the use of a module such as CGI.pm. While often frowned upon by Perl programmers because it's more likely to introduce bugs, bypassing the modules has the advantage of avoiding the overhead of CGI.pm for quick, dirty tasks. This chapter explains the concepts of CGI necessary if you intend to write CGI programs from scratch.
-
CGI.pm is a Perl module designed to facilitate CGI programming. For non-trivial CGI programs, especially ones that need to maintain state over multiple transactions, CGI.pm is indispensable, and is included in the standard Perl distribution as of Perl 5.004. Rather than discuss it in Chapter 8, with the rest of the standard libraries, however, its complexity and importance made it a candidate for its own chapter, Chapter 10.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- A Typical CGI Interaction
- Content preview·Buy reprint rights for this chapterFor an example of a CGI application, suppose you create a guestbook for your website. The guestbook page asks users to submit their first name and last name using a fill-in form composed of two input text fields. Figure 9.1 shows the form you might see in your browser window.Figure 9.1: HTML formThe HTML that produces this form might read as follows:
<HTML><HEAD><TITLE>Guestbook</TITLE></HEAD> <BODY> <H1>Fill in my guestbook!</H1> <FORM METHOD="GET" ACTION="/cgi-bin/guestbook.pl"> <PRE> First Name: <INPUT TYPE="TEXT" NAME="firstname"> Last Name: <INPUT TYPE="TEXT" NAME="lastname"> <INPUT TYPE="SUBMIT"> <INPUT TYPE="RESET"> </FORM>
The form is written using special "form" tags, as follows:-
The
<form>
tag defines the method used for the form (either GET or POST) and the action to take when the form is submitted—that is, the URL of the CGI program to pass the parameters to. -
The
<input>
tag can be used in many different ways. In its first two invocations, it creates a text input field and defines the variable name to associate with the field's contents when the form is submitted. The first field is given the variable namefirstname
and the second field is given the namelastname
. -
In its last two invocations, the
<input>
tag creates a "submit" button and a "reset" button. -
The
</form>
tag indicates the end of the form.
When the user presses the "submit" button, data entered into the<input>
text fields is passed to the CGI program specified by theaction
attribute of the<form>
tag (in this case, the /cgi-bin/guestbook.pl program).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- URL Encoding
- Content preview·Buy reprint rights for this chapterBefore data supplied on a form can be sent to a CGI program, each form element's name (specified by the
name
attribute) is equated with the value entered by the user to create a key/value pair. For example, if the user entered "30" when asked for his or her age, the key/value pair would be "age=30". In the transferred data, key/value pairs are separated by the ampersand (&) character.Since under the GET method the form information is sent as part of the URL, form information can't include any spaces or other special characters that are not allowed in URLs, and also can't include characters that have other meanings in URLs, like slashes (/). (For the sake of consistency, this constraint also exists when the POST method is being used.) Therefore, the web browser performs some special encoding on user-supplied information.Encoding involves replacing spaces and other special characters in the query strings with their hexadecimal equivalents. (Thus, URL encoding is also sometimes called hexadecimal encoding.) Suppose a user fills out and submits a form containing his or her birthday in the syntax mm/dd/yy (e.g., 11/05/73). The forward slashes in the birthday are among the special characters that can't appear in the client's request for the CGI program. Thus, when the browser issues the request, it encodes the data. The following sample request shows the resulting encoding:POST /cgi-bin/birthday.pl HTTP/1.0 Content-length: 21 birthday=11%2F05%2F73
The sequence%2F
is actually the hexadecimal equivalent of the slash character.CGI scripts have to provide some way to "decode" the form data that the client has encoded. The best way to do this is to use CGI.pm (covered in Chapter 10) and let someone else do the work for you.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Extra Path Information
- Content preview·Buy reprint rights for this chapterIn addition to passing query strings, you can pass additional data, known as extra path information, as part of the URL. The server gauges where the CGI program name ends; anything following is deemed "extra" and is stored in the environment variable PATH_INFO. The following line calls a script with extra path information:
https://some.machine/cgi-bin/display.pl/cgi/cgi_doc.txt
In this example, we use a script with a .pl suffix to make it clear where the CGI program's path ends and the extra path information begins. Everything after display.pl is the extra path and is placed in the PATH_INFO environment variable. The PATH_TRANSLATED variable is also set, mapping the PATH_INFO to the DOCUMENT_ROOT directory (e.g., /usr/local/etc/httpd/public/cgi/cgi_doc.txt).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI Environment Variables
- Content preview·Buy reprint rights for this chapterMost of the information needed by CGI programs is made available via Unix environment variables. Programs can access this information as they would any environment variable (via the
%ENV
hash in Perl). The table below lists environment variables commonly available through CGI. However, since servers occasionally vary on the names of environment variables they assign, check with your own server documentation for more information.Environment Variable Content Returned AUTH_TYPE The authentication method used to validate a user. See REMOTE_IDENT and REMOTE_USER.CONTENT_LENGTH The length of the query data (in bytes or the number of characters) passed to the CGI program through standard input.CONTENT_TYPE The media type of the query data, such astext/html
.DOCUMENT_ROOT The directory from which web documents are served.GATEWAY_INTERFACE The revision of the Common Gateway Interface that the server uses.HTTP_ACCEPT A list of the media types that the client can accept.HTTP_COOKIE A list of cookies defined for that URL.HTTP_FROM The email address of the user making the query (many browsers do not support this variable).HTTP_REFERER The URL of the document the client read before accessing the CGI program.HTTP_USER_AGENT The browser the client is using to issue the request.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 10: The CGI.pm Module
- Content preview·Buy reprint rights for this chapterCGI.pm is a Perl module for creating and parsing CGI forms. It is distributed with core Perl as of Perl 5.004, but you can also retrieve CGI.pm from CPAN, and you can get the very latest version at any time from
ftp://ftp-hygenome.wi.mit.edu/pub/software/WWW/
.CGI is an object-oriented module. Don't let the object-oriented nature scare you off, though; CGI.pm is very easy to use, as evidenced by its overwhelming popularity among all levels of Perl programmers. To give you an idea of how easy it is to use CGI.pm, let's take a scenario in which a user fills out and submits a form containing her birthday. Without CGI.pm, the script would have to translate the URL-encoded input by hand (probably using a series of regular expressions) and assign it to a variable. For example, you might try something like this:#!/usr/bin/perl # cgi script without CGI.pm $size_of_form_info = $ENV{'CONTENT_LENGTH'}; read ($STDIN, $form_info, $size_of_form_info); # Split up each pair of key=value pairs foreach $pair (split (/&/, $form_info)) { # For each pair, split into $key and $value variables ($key, $value) = split (/=/, $pair); # Get rid of the pesky %xx encodings $key =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg; $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg; # Use $key as index for $parameters hash, $value as value $parameters{$key} = $value; } # Print out the obligatory content-type line print "Content-type: text/plain\n\n"; # Tell the user what they said print "Your birthday is on " . $parameters{birthday} . ".\n";
Regardless of whether this code actually works, you must admit it's ugly. With CGI.pm, the script could be written:#!/usr/bin/perl -w # cgi script with CGI.pm use CGI; $query = CGI::new(); $bday = $query->param("birthday"); print $query->header(); print $query->p("Your birthday is $bday.");
Even for this tiny program, you can see that CGI.pm can alleviate many of the headaches associated with CGI programming.As with any Perl module, the first thing you do is call the module withAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - HTML Tag Generation
- Content preview·Buy reprint rights for this chapterIn addition to the form-generation methods, CGI.pm also includes a group of methods for creating HTML tags. The names of the HTML tag methods generally follow the HTML tag name (e.g.,
p
for<P>
) and take named parameters that are assumed to be valid attributes for the tag (e.g.,img(src=>'camel.gif')
becomes<IMG SRC="camel.gif">
). We do not list all tags in this book; see the CGI.pm manpage for more information, or the book Official Guide to Programming with CGI.pm by Lincoln Stein (John Wiley & Sons, 1998).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Importing Method Groups
- Content preview·Buy reprint rights for this chapterThe syntax for calling CGI methods can be unwieldy. However, you can import individual methods and then call the methods without explicit object calls. The "birthday" example shown earlier could be written even more simply as follows:
#!/usr/bin/perl use CGI param,header,p; $bday = param("birthday"); print header(); print p("Your birthday is $bday.");
By importing theparam
,header
, andp
methods into your namespace, you no longer have to use thenew
constructor (since it is called automatically now), and you don't need to specify a CGI object with every method call.CGI.pm also lets you import groups of methods, which can make your programs much simpler and more elegant. For example, to import all form-creation methods and all CGI-handling methods:use CGI qw/:form :cgi/;
The method groups supported by CGI.pm are:-
:cgi
-
All CGI-handling methods
-
:cgi-lib
-
All methods supplied for backwards compatibility with cgi-lib
-
:form
-
All form-generation methods
-
:html
-
All HTML methods
-
:html2
-
All HTML 2.0 methods
-
:html3
-
All HTML 3.0 methods
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Maintaining State
- Content preview·Buy reprint rights for this chapterOne of the first complications for any nontrivial CGI script is how to "maintain state." Since HTTP is a stateless protocol, there's no built-in mechanism for keeping track of requests from the server end. A CGI transaction involving multiple forms, therefore, needs to find a way to remember information supplied on previous forms. One way to deal with this issue is to use cookies, which allow the CGI program to save information on the browser's end; but not all browsers support cookies, and some users are uncomfortable with the perceived privacy infringement associated with cookies.CGI.pm simplifies maintaining state without cookies. When a CGI.pm script is called multiple times, the input fields are given default values from the previous invocation.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Named Parameters
- Content preview·Buy reprint rights for this chapterFor most CGI.pm methods, there are two syntax styles. In the "standard" style, the position of the parameters determines how they will be interpreted—for example, parameter 1 is the name that the script should assign, parameter 2 is the initial value, etc. For example:
print $query=textfield('username', 'anonymous');
In the "named parameters" style, the parameters can be assigned like a hash, and the order doesn't matter. For example:print $query->textfield(-name=>'name', -default=>'value');
If you want to use named parameters, just call theuse_named_parameters
method early in the script.Which syntax style should you use? It depends on how lazy you are and much control you need. Generally, "standard" syntax is faster to type. However, it is also harder to read, and there are many features that are simply not available using standard syntax (such as JavaScript support). In general, we recommend using the "named parameters" syntax for all but the most trivial scripts.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Using JavaScript Features
- Content preview·Buy reprint rights for this chapterCGI.pm supports JavaScript scripting by allowing you to embed a JavaScript script into the HTML form within
<SCRIPT>
tags, and then calling the script using the-script
parameter to thestart_html
method. You can then call the JavaScript functions as appropriate to the form elements.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Debugging
- Content preview·Buy reprint rights for this chapterA complication of writing CGI scripts is that when debugging the script, you have to wrestle with the web server environment. CGI.pm provides support for debugging the script on the command line.If you run the script on the command line without arguments, you will be placed into an "offline" mode, in which name-value pairs can be entered one-by-one. When you press CTRL-D, the script runs. For example:
% birthday (offline mode: enter name=value pairs on standard input) birthday=6/4/65 ^D Content-type: text/html <P>Your birthday is 6/4/65.</P>
You can also supply the name/value parameters directly on the command line. For example:% test birthday=6/4/65 Content-type: text/html <P>Your birthday is 6/4/65.</P>
Multiple values can be separated by spaces (as separate arguments on the command line) or by ampersands (as in URL-encoded syntax). In fact, you can use URL-encoded syntax on the command line. This makes it easy to supply raw CGI input to the script for testing purposes. Just remember to protect the ampersand from the shell.% test 'birthday=6%2f4%2f65&name=Fred%20Flintstone' Content-type: text/html <P>Fred Flintstone, your birthday is 6/4/65.</P>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - CGI.pm Reference
- Content preview·Buy reprint rights for this chapterThe following methods are supported by CGI.pm:accept$query ->accept([' content_type '])DescriptionReturns a list of media types that the browser accepts.
- content_type
-
If specified, returns instead the browser's preference for the specified content type, between 0.0 and 1.0.
append$query ->append(-name=>' name',-values=>' value ')DescriptionAppends a value or list of values to the named parameter.- -name=>' name'
-
The parameter to be appended.
- -values=>' value'
-
The value to append. Multiple values can be specified as a reference to an anonymous array.
auth_typeAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 11: Web Server Programming with mod_perl
- Content preview·Buy reprint rights for this chapterA common criticism of CGI is that it requires forking extra processes each time a script is executed. If you only have a few hits an hour, or even a few hits a minute, this isn't a big deal. But for a high-traffic site, lots of CGI scripts repeatedly spawning can have an unfortunate effect on the machine running the web server. The CGI scripts will be slow, the web server will be slow, and other processes on the machine will come to a crawl.The solution to this problem is mod_perl. mod_perl, written by Doug MacEachern and distributed under CPAN, embeds the Perl interpreter directly into the web server. The effect is that your CGI scripts are precompiled by the server and executed without forking, thus running much more quickly and efficiently. Furthermore, CGI efficiency is only one facet of mod_perl. Since mod_perl is a complete Apache/Perl hybrid, other benefits to mod_perl include:
-
Writing server-side includes in Perl
-
Embedding Perl code into the Apache configuration files
-
Writing complete Apache modules in Perl
mod_perl is not a Perl module. It is a module of the Apache server, which is currently the most commonly used web server. With mod_perl, you can use Apache configuration directives not only to process CGI scripts much more efficiently, but also to handle all stages in processing a server request.mod_perl embeds a copy of the Perl interpreter into the Apache httpd executable, providing complete access to Perl functionality within Apache. This enables a set of mod_perl-specific configuration directives, all of which start with the stringPerl*
. Most of these directives are used to specify handlers for various stages of the request, but not all. In addition, mod_perl lets you embed Perl code into your Apache configuration files (within<Perl> … </Perl>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Design of mod_perl
- Content preview·Buy reprint rights for this chaptermod_perl is not a Perl module. It is a module of the Apache server, which is currently the most commonly used web server. With mod_perl, you can use Apache configuration directives not only to process CGI scripts much more efficiently, but also to handle all stages in processing a server request.mod_perl embeds a copy of the Perl interpreter into the Apache httpd executable, providing complete access to Perl functionality within Apache. This enables a set of mod_perl-specific configuration directives, all of which start with the string
Perl*
. Most of these directives are used to specify handlers for various stages of the request, but not all. In addition, mod_perl lets you embed Perl code into your Apache configuration files (within<Perl> … </Perl>
directives) and allows you to use Perl for server-side includes.It might occur to you that sticking a large program into another large program makes a very, very large program. mod_perl certainly makes httpd significantly bigger. If you have limited memory capacity, mod_perl may not be for you. There are several ways to minimize the size of Apache with mod_perl (which you can find in the mod_perl manpage or the FAQs), ranging from fiddling with Apache configuration directives to building Perl with reduced memory consumption.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Installing mod_perl
- Content preview·Buy reprint rights for this chapterIf you already have Apache installed on your machine, you will have to rebuild it with mod_perl. You can get the source for both Apache and mod_perl from
https://www.apache.org/
. (You can also get mod_perl from CPAN.) If there isn't already an Apache httpd in the Apache source tree, you must build one. Then build mod_perl as directed in the INSTALL file for the mod_perl distribution.As we've mentioned, mod_perl allows you to hook in Perl modules as handlers for various stages of a request. By default, however, the only callback hook that is enabled isPerlHandler
, which is the one used to process content (i.e., a CGI document). If you want to use other hooks, for example to extend Apache's logging facilities via thePerlLogHandler
directive, you'll need to specify it at build time as directed in the INSTALL file. For example:% perl Makefile.PL PERL_LOG=1
The mod_perl Makefile replaces the httpd in the Apache source tree with a Perl-enabled one. When you install mod_perl, it not only installs the new httpd into your system area, it also installs several Perl modules including Apache::Registry.At the time of this writing, both Apache and mod_perl are being ported to Win32. However, mod_perl will only run with the standard Perl Win32 port (not ActiveState's). The INSTALL.win32 file contains the instructions for installing mod_perl under Win32.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - mod_perl Handlers
- Content preview·Buy reprint rights for this chapterTo understand mod_perl, you should understand how the Apache server works. When Apache receives a request, it processes it in several stages. First, it translates the URL to the associated resource (i.e., filename, CGI script, etc.) on the server machine. Then it checks to see if the user is authorized to access that resource, perhaps by requesting and checking an ID and password. Once the user has passed inspection, the server figures out what kind of data it's sending back (e.g., it decides a file ending in .html is probably a
text/html
file), creates some headers, and sends those headers back to the client with the resource itself. When all is said and done, the server makes a log entry.At each stage of this process, Apache looks for routines to "handle" the request. Apache supplies its own handlers; for example, one of the default handlers iscgi-script
, often seen applied to /cgi-bin:<Location /cgi-bin> ... SetHandler cgi-script ... </Location\>
mod_perl allows you to write your own handlers in Perl, by embedding the Perl runtime library directly into the Apache httpd server executable. To use mod_perl for CGI (which is all that most people want to do with it), you assign theSetHandler
directive toperl-script
, and then assign the mod_perl-specificPerlHandler
directive to a special Perl module called Apache::Registry.SetHandler perl-script PerlHandler Apache::Registry
PerlHandler
is the mod_perl handler for the content retrieval stage of the transaction.To use other handlers, you don't need to reassignSetHandler
. For example, to identify a handler for the logging stage of the request:<Location /snoop/> PerlLogHandler Apache::DumpHeaders </Location\>
In order for this to work, mod_perl must have been built with the logging hooks enabled (as described in the previous section), and the Apache::DumpHeaders module must have been installed. mod_perl looks in Apache::DumpHeaders for a routine calledAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Running CGI Scripts with mod_perl
- Content preview·Buy reprint rights for this chapterWhat most people want to do with mod_perl is improve CGI performance. The mod_perl installation assumes this request by enabling the
PerlHandler
callback hook by default, and by installing the Apache::Registry module.PerlHandler
is the handler used for the content retrieval stage of the server transaction. Apache::Registry is the Perl module that emulates the CGI environment so you can use "standard" Perl CGI scripts with mod_perl without having to rewrite them (much). This is by far the cheapest way to get improved CGI performance.With Apache::Registry, each individual CGI program is compiled and cached the first time it is called (or whenever it is changed), and then remains available for all subsequent instances of that CGI script. This process avoids the costs of startup time.Whereas most CGI scripts are kept in /cgi-bin/, scripts that use Apache::Registry are placed in a separate directory, e.g., /perl-bin/. The access.conf Apache configuration file needs to point to this directory by setting an alias and defining a handler for this new location.Alias /perl-bin/ /usr/local/apache/perl-bin/ <Location /perl-bin> SetHandler perl-script PerlHandler Apache::Registry PerlSendHeader On Options ExecCGI </Location>
Instead of using thecgi-script
handler, we use theperl-script
handler to give control to mod_perl. Next, thePerlHandler
directive tells mod_perl that the Apache::Registry module should be used for serving all files in that directory.PerlSendHeader
is another mod_perl-specific directive; in this case, it tells mod_perl to send response lines and common headers—by default, none are sent. (For NPH scripts, you'll want to turn this feature off again.)Options ExecCGI
is a standard Apache header needed to tell Apache to treat the script as a CGI script.If you want to load Perl modules in addition to Apache::Registry, you can use the PerlModule directive:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Server-Side Includes with mod_perl
- Content preview·Buy reprint rights for this chapterServer-side includes (SSI) are tags embedded directly into an HTML file that perform special functions. They are most commonly used for running CGI scripts and displaying the result; most web page counters are performed using SSI.If you use mod_perl with mod_include (another Apache server module), you can embed Perl subroutines into SSI directives. For example:
<!--#perl sub="sub {print ++Count}" -->
The Apache::Include module lets you include entire Apache::Registry scripts:<!--#perl sub="Apache::Include" arg="/perl-bin/counter.pl"-->
You could have used standard SSI to include a CGI script for the same purpose, but this way is faster. To use mod_include with mod_perl, you need to configure mod_perl to do so at compile time.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - <Perl> Sections
- Content preview·Buy reprint rights for this chapterWith mod_perl, you can use Perl in Apache configuration files. What this means is that you can make your Apache configuration much more flexible by using conditionals.Any Perl code in Apache configuration files should be placed between
<Perl>
and</Perl>
directives. This code can define variables and lists that are used by mod_perl to assign the associated Apache configuration directives; for example, assigning the$ServerAdmin
variable will redefine theServerAdmin
Apache configuration directive.Suppose you share the same Apache configuration files across multiple servers, and you only want to allow personal directories on one of them. You can use Perl directives like this:<Perl> if (`hostname` =~ /public/) { $UserDir = "public.html"; } else { $UserDir = "DISABLED"; } 1; </Perl>
Directive blocks (such as<Location>…</Location\>
) can be represented as a hash. For example:<Perl> $Location{"/design_dept/"} = { DefaultType => 'image/gif', FancyIndexing => 'On' } </Perl>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Apache:: Modules
- Content preview·Buy reprint rights for this chapterApache::Registry is the most commonly used mod_perl module. But there are many more, all available on CPAN. The following table lists the Apache::* modules and which handler they're designed to be used with, but you should also check the apache-modlist.html file on CPAN for the very latest listing.
PerlHandler Apache::CallHandler Maps filenames to subroutine calls Apache::Dir Controls directory indexing Apache::Embperl Embeds Perl code in HTML files Apache::ePerl Embedded Perl (ePerl) emulation Apache::FTP Emulates an FTP proxy Apache::GzipChain Compresses output from another handler Apache::JavaScript Generates JavaScript code Apache::OutputChain Chains multiple handlers via "filter" modules Apache::PassFile Sends files via OutputChain Apache::Registry Runs unaltered CGI scripts Apache::RobotRules Enforces robots.txt rules Apache::Sandwich Adds per-directory headers and footers Apache::VhostSandwich Adds headers and footers for virtual hosts Apache::SSI Implements server-side includes in Perl Apache::Stage Manages a document staging directory Apache::WDB Queries databases via DBI PerlHeaderParserHandler Apache::AgentDeny Denies abusive clients PerlAuthenHandler Apache::Authen Authenticates users Apache::AuthCookie Authenticates and authorizes users via cookies Apache::AuthenDBI Authenticates via Perl's DBI Apache::AuthExpire Expires authentication credentialsApache::AuthenGSS Authenticates users with Generic Security ServiceApache::AuthenLDAP Authenticates users with LDAP Apache::AuthNIS Authenticates users with NIS Apache::BasicCookieAuth Accepts cookie or basic authentication credentials Apache::DBILogin Authenticates using a backend database Apache::DCELogin Authenticates within a DCE login context Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 12: Databases and Perl
- Content preview·Buy reprint rights for this chapterSince one of Perl's greatest strengths is working with text, a genuine concern is how to store data. Flat files are one possibility, but don't scale very well, to say the least. Instead, you'll need to use a database.There are two general solutions to using databases with Perl. For simple database purposes, DBM (Database Management) will serve your needs. DBM is a library supported by many (if not all) Unix systems and many non-Unix systems as well. If you use DBM with Perl, you can manipulate databases just like any hash.For more elaborate databases with SQL interfaces, you can get a complete database product or shareware equivalent (depending on your needs) and use DBI and DBD. DBI is a module that provides a consistent interface for database solutions. A DBD is a database-specific driver that translates DBI calls as needed for that database.In this chapter, we'll quickly cover DBM and then talk more at length about DBI/DBD.DBM is a simple database management facility for Unix systems. It allows programs to store a collection of key-value pairs in binary form, thus providing rudimentary database support for Perl. Practically all Unix systems support DBM, and for those that don't, you can get Berkeley DB from
https://www.sleepycat.com/db
.To use DBM databases in Perl, you can associate a hash with a DBM database through a process similar to opening a file. This hash (called a DBM array) is then used to access and modify the DBM database. To associate a DBM database with a DBM array, you can use either thedbmopen
function or thetie
function with a DBM-style module. (dbmopen
is actually just a front-end totie
.) For example, withdbmopen
:dbmopen(%ARRAYNAME, "dbmfilename", $mode);
or (usingtie
with the DB_File module):use DB_File; tie(%ARRAYNAME, "DB_File", "dbmfilename");
The%ARRAYNAME
parameter is a Perl hash. (If it already has values, the values are discarded.) This hash becomes connected to the DBM database calledAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - DBM Databases and DBM Hashes
- Content preview·Buy reprint rights for this chapterDBM is a simple database management facility for Unix systems. It allows programs to store a collection of key-value pairs in binary form, thus providing rudimentary database support for Perl. Practically all Unix systems support DBM, and for those that don't, you can get Berkeley DB from
https://www.sleepycat.com/db
.To use DBM databases in Perl, you can associate a hash with a DBM database through a process similar to opening a file. This hash (called a DBM array) is then used to access and modify the DBM database. To associate a DBM database with a DBM array, you can use either thedbmopen
function or thetie
function with a DBM-style module. (dbmopen
is actually just a front-end totie
.) For example, withdbmopen
:dbmopen(%ARRAYNAME, "dbmfilename", $mode);
or (usingtie
with the DB_File module):use DB_File; tie(%ARRAYNAME, "DB_File", "dbmfilename");
The%ARRAYNAME
parameter is a Perl hash. (If it already has values, the values are discarded.) This hash becomes connected to the DBM database calleddbmfilename
. This database may be stored on disk as a single file, or as two files called dbmfilename.dir and dbmfilename.pag, depending on the DBM implementation.The$mode
parameter is a number that controls the permissions of the pair of files if the files need to be created. The number is typically specified in octal. If the files already exist, this parameter has no effect. For example:dbmopen(%BOOKS, "bookdb", 0666); # open %BOOKS onto bookdb
This invocation associates the hash%BOOKS
with the disk files bookdb.dir and bookdb.pag in the current directory. If the files don't already exist, they are created with a mode of 0666, modified by the current umask.The return value fromdbmopen
is true if the database could be opened or created, and false otherwise, just like theopen
function. If you don't want the files created, use a$mode
value ofundef
.Once the database is opened, anything you do to the DBM hash is immediately written to the database. See Chapter 4, for more information on hashes.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Design of DBI
- Content preview·Buy reprint rights for this chapterIf DBM is too primitive for your database requirements, you'll have to use a more sophisticated database package. Options include the commercial products Oracle, Sybase, and Informix, and the publically-available msql and mysql.Prior to Perl Version 5 and DBI, the problem was that with all the database packages to choose from, there was no way to universalize database support for Perl. You'd have to rebuild the Perl executable itself against libraries that included subroutines for direct access to the database package. For example, sybperl and oraperl are both packages for building Perl Version 4 with Sybase and Oracle calls embedded, respectively. An application written for sybperl would not be portable to Oracle, or vice-versa. However, since current versions of Perl support binary extension loading at runtime, database support can now be added at runtime, which simplifies adding database interfaces to Perl programs while keeping the size of the Perl binary to a minimum.Support for binary extensions doesn't mean that database access has been standardized. There are still many database extensions to Perl, each with a different API. However, they all share a strikingly similar set of commands: connect to the database, issue queries, fetch results, and disconnect. This consistency has made it possible to develop a standard set of methods to work with any database. DBI defines a set of functions, variables, and conventions that provide a consistent database programming interface for Perl.Although DBI itself is language-independent, most DBI drivers require applications to use a dialect of SQL (structured query language) to interact with the database engine. SQL is a standard that was developed to allow programmers to manipulate relational databases. There are many implementations of SQL, and each database server adds nuances that deviate from the standard.The success of DBI is that it is only half of the story. The other half is a DBD, or a database driver. DBI provides the interface and framework for the drivers, but it's the database drivers that do the real work. Drivers implement the DBI methods for the private interface functions of the corresponding database engine.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - DBI Methods
- Content preview·Buy reprint rights for this chapterThe following methods are available under DBI:available_drivers@drivers = DBI->available_drivers([nowarn])DescriptionReturns a list of available drivers by searching
@INC
for the presence of DBD::* modules.- nowarn
-
A boolean value specifying whether to suppress warnings if some drivers are hidden by others of the same name in earlier directories. Default is false (don't suppress).
bind_param$result = $st_handle ->bind_param(n, value [, type ])DescriptionBinds a value with a placeholder in a prepared statement.- n
-
The parameter number to bind.
- value
-
The value to associate with parameter n.
- type
-
The data type for the placeholder. The type can also be specified as an anonymous list (
{TYPE =>
type
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - DBI Environment Variables
- Content preview·Buy reprint rights for this chapterThe following environment variables are defined for use with DBI:
- DBI_DSN
-
The data source value to use if none is specified with the
connect
method. - DBI_DRIVER
-
The driver to use if none is specified with the
connect
method. - DBI_USER
-
The username to use if none is specified with the
connect
method. - DBI_PASS
-
The password to use if none is specified with the
connect
method. (For security purposes, this environment variable should not be set except for testing.) - DBI_TRACE
-
Enables tracing behavior as with the
trace
method. DBI_TRACE can be set to any of the following values:-
0
-
Disables the trace.
-
1
-
Traces the execution of the DBI.
-
2
-
Outputs detailed call trace information including parameters and return values.
-
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 13: Sockets
- Content preview·Buy reprint rights for this chapterWhy build networking functionality into your Perl scripts? You might want to access your email remotely, or write a simple script that updates files on a FTP site. You might want to check up on your employees with a program that searches for Usenet postings that came from your site. You might want to check a web site for any recent changes, or even write your own home-grown web server. The network is the computer these days, and Perl makes network applications easy.Perl programmers have their choice of modules for doing common tasks with network protocols; Chapter 14, through Chapter 17, cover the modules for writing email, news, FTP, and web applications in Perl. If you can do what you want with the available modules, you're encouraged to jump to those chapters and skip this one. However, there will be times that you'll have to wrestle with sockets directly, and that's where this chapter comes in.Sockets are the underlying mechanism for networking on the Internet. With sockets, one application (a server) sits on a port waiting for connections. Another application (the client) connects to that port and says hello; then the client and server have a chat. Their actual conversation is done with whatever protocol they choose—for example, a web client and server would use HTTP, an email server would use POP3 and SMTP, etc. But at the most basic level, you might say that all network programming comes down to opening a socket, reading and writing data, and closing the socket again.You can work with sockets in Perl at various levels. At the lowest level, Perl's built-in functions include socket routines similar to the system calls in C of the same name. To make these routines easier to use, the Socket module in the standard library imports common definitions and constants specific to your system's networking capabilities. Finally, the IO::Socket module provides an object interface to the socket functions through a standard set of methods and options for constructing both client and server communications programs.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Built-in Socket Functions
- Content preview·Buy reprint rights for this chapterPerl provides built-in support for sockets. The following functions are defined specifically for socket programming. For full descriptions and syntax, see Chapter 5.
-
socket
-
Initializes a socket and assigns a filehandle to it.
-
bind
-
For servers, associates a socket with a port and address. For clients, associates a socket with a specific source address.
-
listen
-
(Server only.) Waits for incoming connection with a client.
-
accept
-
(Server only.) Accepts incoming connection with a client.
-
connect
-
(Client only.) Establishes a network connection on a socket.
-
recv
-
Reads data from a socket filehandle.
-
send
-
Writes data to a filehandle.
-
shutdown
(orclose
) -
Terminates a network connection.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The IO::Socket Module
- Content preview·Buy reprint rights for this chapterThe IO::Socket module included in the core Perl distribution provides an object-oriented approach to socket programming. This module provides a convenient way to handle the large number of options you have to deal with, and it handles the laborious task of forming addresses. IO::Socket is built upon the Socket module provided in the standard library. It inherits from IO::Handle, which supports a class of filehandle objects for much of the IO library. The following IO::Socket functions are simply frontends for the corresponding built-in functions and use the same syntax:
socket socketpair bind listen send recv peername (same as getpeername) sockname (same as getsockname)
Theaccept
function in IO::Socket is slightly different from the equivalent function, however, and is described later in the chapter.IO:Socket contains two subclasses: INET and UNIX. The INET subclass is used to create and manipulate Internet-domain sockets, such as the ones used in the examples. The UNIX subclass creates Unix domain sockets.IO::Socket greatly simplifies the implementation of a socket for client communications. The following example creates an Internet-domain socket (using the INET subclass) and attempts to connect to the specified server:use IO::Socket; $sock = new IO::Socket::INET (PeerAddr => 'www.ora.com', PeerPort => 80, Proto => 'tcp'); die "$!" unless $sock;
IO::Socket::INET::new
creates an object containing a socket filehandle and connects it to the host and port specified inPeerAddr
andPeerPort
. The object$sock
can then be written to and read from like other socket filehandles.On the server side, IO::Socket provides a nice wrapper for creating server sockets. The wrapper encompasses thesocket
,Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 14: Email Connectivity
- Content preview·Buy reprint rights for this chapterElectronic mail is arguably the most essential Internet application. In fact, for many people, it's their introduction to the Internet. Thus the Perl modules that deal with email are among the most useful modules. There are two major groups of modules that provide email capabilities. The first group is Graham Barr's libnet collection, which contains packages for developing client-side applications over the Internet in Perl. Table 14.1 lists some of the protocols implemented by the libnet modules.
Table 14.1: Protocols Implemented by the libnet Modules Protocol Module Description POP3 Net::POP3 Post Office Protocol, for reading emailSMTP Net::SMTP Simple Mail Transfer Protocol, for sending emailFTP Net::FTP File Transfer Protocol, for transferring files between hostsNNTP Net::NNTP Network News Transfer Protocol, for reading Usenet newsIn this chapter, we discuss Net::SMTP and Net::POP3. Chapter 15, talks about Net::NNTP, and Chapter 16, discusses Net::FTP. Other libnet modules, such as Net::SNPP and Net::Time, are not described here, but you can get information about them from CPAN or with the perldoc command if libnet is installed on your system.The second group of mail-related modules are the Mail modules, many of which were also written by Graham Barr. They can be found on CPAN as the MailTools collection. The Mail modules also include Mail::Folder and its subclasses, written by Kevin Johnson, and Mail::POP3Client, by Sean Dowd. This chapter describes the following subset of the Mail modules:- Mail::Send
-
Built on top of Mail::Mailer, providing better control of mail headers.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The Net Modules
- Content preview·Buy reprint rights for this chapterNet::SMTP and Net::POP3 are the modules for sending and receiving email via the SMTP and POP3 protocols. When you use these modules, you are working at the socket level; they directly implement the Internet protocols for sending and receiving mail as defined in the relevant RFCs—RFC 821 for SMTP and RFC 1081 for POP3.The Simple Mail Transfer Protocol, or SMTP, is responsible for clients negotiating RCPT ("to") and FROM ("from") requests with an SMTP server, sending data to the SMTP server, and then sending an end-of-data indicator. Net::SMTP is a subclass of Net::Cmd and IO::Socket::INET that implements an interface to the SMTP and ESMTP protocols. These protocols send mail by talking to an SMTP server through a socket, as described in RFC 821.When would you want to use Net::SMTP instead of sending mail with an external program? Since socket communications don't involve spawning an external program, your programs won't suffer from the overhead associated with running an extra process. Talking to SMTP is convenient for sending a volume of mail messages. Naturally, your server must have an SMTP server running or a remote mailhost must allow you to talk to it; otherwise you won't be able to use this module. That's when you can turn to Mail::Mailer or Mail::Send and let them provide an interface to an external mail program for you. This is the case, for example, with home computers, which don't generally run their own SMTP server.The SMTP protocol defines the set of commands a client sends to an SMTP server, which is generally bound to port 25 of a mailhost. Requests and responses are negotiated between client and server.When a client negotiates an SMTP session with a server, the server tells the client that it's listening. Once you're connected, you introduce yourself to the server by issuing a HELO command. The HELO command accepts one parameter—your hostname—and defaults to your remote hostname if you don't specify one. If the command is successful, the server sends a 250 response, as follows:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The Mail Modules
- Content preview·Buy reprint rights for this chapterThe Mail modules operate at a higher level than the Net modules, interacting with external mail packages such as mail, mailx, sendmail, or a POP3 server in the case of POP3Client. This section describes some of the MailTools modules, Mail::Folder, and Mail::POP3Client.The Mail::Mailer module interacts with external mail programs. When you use Mail::Mailer or create a new Mail::Mailer object, you can specify which mail program you want your program to talk to:
use Mail::Mailer qw(mail);
Another way to specify the mailer is:use Mail::Mailer; $type = 'sendmail'; $mailprog = Mail::Mailer->new($type);
where$type
is the mail program. Once you've created a new object, use theopen
function to send the message headers to the mail program as a hash of key/value pairs, where each key represents a header type, and where the value is the value of that header:# mail headers to use in the message %headers = ( 'To' => 'you@mail.somename.com', 'From' => 'me@mail.somename.com', 'Subject' => 'working?' );
This code represents headers where the recipient of the mail message is you@mail.somename.com, the mail was sent from me@mail.somename.com, and the subject of the mail message is "working?"Once%headers
has been defined, it is passed toopen
:$mailprog->open(\%headers);
You then send the body of the message to the mail program:print $mailprog "This is the message body.\n";
Now, close the program when the message is finished:$mailprog->close;
A practical example of using Mail::Mailer might be a command-line-driven application that works much like the Unix mail program, either reading STDIN until EOF or mailing a file specified on the command line.Mail::Mailer uses the environment variable PERL_MAILERS to augment or modify the built-in mailer selection. PERL_MAILERS is specified in the following format:"type1:mailbinary1;mailbinary2;...:type2:mailbinaryX;...:..."
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 15: Usenet News
- Content preview·Buy reprint rights for this chapterUsenet is a collection of bulletin-board-like newsgroups on the Internet, covering thousands of topics. Whatever your interest, chances are you'll find a newsgroup in which it is discussed.Usenet has been around since late 1979. The current implementation is based on the Network News Transfer Protocol (NNTP), defined in RFC 977 and released in March 1986. Information is propagated through Usenet by a system of newsfeeds in which one site requests a newsfeed from another site, and a third site requests a newsfeed from the second site, etc. There is no central Usenet authority—like Perl, it runs on the spirit of cooperation and sharing. When you run a news reader, such as tin or the news reader in a web browser, your client software talks to the NNTP server on the news host. When you post a message to a newsgroup, this posting is received by your NNTP server and passed on to other servers throughout the distribution area you specified for the posting. Each server periodically receives updated newsgroup information and newly posted news articles.This chapter explores NNTP commands and responses. It introduces Net::NNTP, which implements NNTP commands and simplifies the process of writing a Perl-based NNTP news client. It also describes News::Newsrc, a module that provides methods for managing a .newsrc file.There are two kinds of NNTP commands—the official set of commands as defined in RFC 977 and a number of extensions that have been added since the RFC was written. The extensions are described in an IETF Internet Draft document, "Common NNTP Extensions" by Stan Barber, which can be found at
ftp://ftp.academ.com/pub/nntp/ietf/nntpext.txt
.Before you write your own news client, you should have some idea of how the NNTP protocol works. Like other servers, an NNTP server is bound to a port (usually port 119). It listens for incoming connections, takes the appropriate action, and returns a response to the client. When a news client connects with an NNTP server, or to the port on which the NNTP server is running, a message like the following is produced:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The NNTP Protocol
- Content preview·Buy reprint rights for this chapterBefore you write your own news client, you should have some idea of how the NNTP protocol works. Like other servers, an NNTP server is bound to a port (usually port 119). It listens for incoming connections, takes the appropriate action, and returns a response to the client. When a news client connects with an NNTP server, or to the port on which the NNTP server is running, a message like the following is produced:
Trying 0.0.0.0... Connected to hostname.mydomain.com. Escape character is '^]'. 200 newshost.mydomain.com InterNetNews NNRP server INN 1.5.1 17-Dec-1996 ready (posting ok).
Many NNTP servers understand the help (or HELP) command. When a client issues a help command, many NNTP servers respond with a list of all available commands. For example:200 news.mydomain.com InterNetNews NNRP server INN 1.5.1 17-Dec-1996 ready (posting ok). HELP 100 Legal commands authinfo user Name|pass Password|generic <prog> <args> article [MessageID|Number] body [MessageID|Number] date group newsgroup head [MessageID|Number] help ihave last list [active|active.times|newsgroups|distributions|distrib.pats|overview.fmt |subscriptions] listgroup newsgroup mode reader newgroups yymmdd hhmmss ["GMT"] [<distributions>] newnews newsgroups yymmdd hhmmss ["GMT"] [<distributions>] next post slave stat [MessageID|Number] xgtitle [group_pattern] xhdr header [range|MessageID] xover [range] xpat header range|MessageID pat [morepat...] xpath MessageID Report problems to <usenet@news.mydomain.com> .
After connecting to the NNTP server, you can get a list of available newsgroups with the list active command, and you can then select a newsgroup. If you were to connect directly to news.mydomain.com and use the group command to select the newsgroup local.test, your session might look like this:200 news.mydomain.com InterNetNews NNRP server INN 1.5.1 17-Dec-1996 ready (posting ok). group local.test 211 4 1 4 local.test QUIT 205 .
The four numbers (in this example,Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::NNTP
- Content preview·Buy reprint rights for this chapterNet::NNTP is one of the libnet modules. It provides methods for programming a news client to interface with an NNTP server. Net::NNTP implements the NNTP protocol as defined in RFC 977, as well as a number of extensions defined in the IETF Internet Draft document mentioned earlier.For example, the following code:
$nntp->post(@message);
is equivalent to issuing the post command and associated X-headers directly to an NNTP server on port 119.To use Net::NNTP, create a new Net::NNTP object:use Net::NNTP; $nntp = Net::NNTP->new; # Use default port and options
Once you've created the object, you can use any of the Net::NNTP methods on that object. The Net::NNTP methods generally parallel the functionality of the raw NNTP commands. Your news client can be written to perform many functions, including:-
Authenticating a user to the server
-
Listing available newsgroups
-
Retrieving news headers and articles
-
Extracting headers
-
Checking for new articles
-
Posting articles
-
Listing information such as active messages in a newsgroup, new newsgroups, valid distribution areas, or message IDs of newly arrived messages
Net::NNTP includes methods that implement many of the extensions to RFC 977; the description indicates if a method is an extension. Extensions that are not supported by Net::NNTP are AUTHINFO GENERIC, XINDEX, XSEARCH, and XTHREAD. In addition, some extensions supported by Net::NNTP may not be supported by a particular server.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The News::Newsrc Module
- Content preview·Buy reprint rights for this chapterMost Unix-based newsreaders parse and extract your newsgroup information from a .newsrc file. This file contains an entry for each newsgroup, with the name of the group and a comma-separated list of article numbers from 1 to the current article. The first entry in the list shows articles that have been read; the remaining entries list unread articles. Each entry also has a colon (
:
) following the name if you are subscribed to that newsgroup or an exclamation point (!
) if you are currently unsubscribed.In order for you to read a newsgroup, your newsreader needs to be connected to an NNTP server. The newsreader then checks the .newsrc entry for that newsgroup to determine which articles you haven't yet read, and displays the first unread article. You can then read the articles sequentially or select which articles you want to read. When you "catch-up" a newsgroup by marking all the articles as "read," or when you exit from the newsreader program, your .newsrc file is updated to reflect your activity during that session.The News::Newsrc module provides methods for managing your .newsrc file. Some of the functions it provides include letting you add, remove, or reorder newsgroups; subscribe to or unsubscribe from newsgroups; and mark articles as read or unmark them. Unless you tell it to rearrange the order of the newsgroups in .newsrc, News::Newsrc leaves the order unchanged.new$newsrc = new News::NewsrcDescriptionConstructor. Creates a new News::Newsrc object that contains no newsgroups.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 16: FTP
- Content preview·Buy reprint rights for this chapterThe File Transfer Protocol (FTP) is a popular means of transferring files between computers. FTP communication follows the client/server model: the client initiates a conversation by sending commands, and the server responds with messages and status codes, as well as by sending or receiving files. This chapter discusses two FTP-related modules included in the libnet distribution: Net::FTP, which provides a number of wrapper functions for implementing the client side of FTP, and Net::Netrc, which provides an interface for getting information from a .netrc file.The FTP protocol permits two-way file transactions, in which files can be sent to or taken from an FTP server. These transactions involve the local filesystem (on the client side) and the remote filesystem (on the server side). When a file is transferred between the local and remote systems, its filename on the destination system is the same as on the source system unless you specify a new filename.The FTP protocol also lists the types of files that can be transferred. These types define (among many other things) how end-of-line characters are handled for different types of files.When a server accepts FTP requests, it opens a port (generally port 21) for incoming connections and authenticates clients based on account or anonymous privileges. A user may log in with a legitimate account on that machine, provide her own password, and be given access to any file she normally has access to under the Unix shell. Many servers also allow "anonymous" FTP, in which users log in with the name "anonymous" and use their email address as the password. They are then granted restricted access to a limited portion of the filesystem.The FTP commands defined in RFC 959 are listed in the following table:CommandMeaning
ABOR Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The FTP Protocol
- Content preview·Buy reprint rights for this chapterWhen a server accepts FTP requests, it opens a port (generally port 21) for incoming connections and authenticates clients based on account or anonymous privileges. A user may log in with a legitimate account on that machine, provide her own password, and be given access to any file she normally has access to under the Unix shell. Many servers also allow "anonymous" FTP, in which users log in with the name "anonymous" and use their email address as the password. They are then granted restricted access to a limited portion of the filesystem.The FTP commands defined in RFC 959 are listed in the following table:CommandMeaning
ABOR Abort previous FTP commandACCT Specify the user's accountALLO Tell server to allocate additional storage for new fileAPPE Tell server to append to an existing fileCDUP Change to parent directoryCWD Change directoryDELE Delete a fileHELP Get helpLIST List files for displayMKD Make a directoryMODE Specify the data transfer modeNLST List files for additional processingNOOP No-opPASS Specify the user's passwordPASV Tell server to go into "passive" modePORT Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Net::FTP
- Content preview·Buy reprint rights for this chapterNet::FTP is used to transfer files from remote hosts. Using Net::FTP, you can write simple FTP clients that transfer files from remote servers based on information passed on the command line or from hard-coded variables. Here is an example of a client that connects to a remote FTP server and gets a file from the server:
#!/usr/local/bin/perl -w use Net::FTP; $hostname = 'remotehost.com'; $username = 'anonymous'; $password = 'myname@mydomain.com'; # Hardcode the directory and filename to get $home = '/pub'; $filename = 'TESTFILE'; # Open the connection to the host $ftp = Net::FTP->new($hostname); # construct object $ftp->login($username, $password); # log in $ftp->cwd($home),"\n"; # change directory print $ftp->ls($home),"\n"; # Now get the file and leave $ftp->get($filename); $ftp->quit;
FTP clients have also been integrated with most World Wide Web browsers, using ftp:// in place of https://. When the URL points to a directory, the browser displays a listing of the directory, where each filename is a link to that file. When the URL points directly to a file, the remote file is downloaded.Here's an example that uses Net::FTP to list files from a remote FTP server on a web page, with a link from each file to the URL of the file on the remote site:#!/usr/local/bin/perl -w use Net::FTP; $hostname = 'remotehost.com'; # ftp host $username = 'anonymous'; # username $password = 'myname@mydomain.com'; # password $home = '/pub'; $ftp = Net::FTP->new($hostname); # Net::FTP constructor $ftp->login($username, $password); # log in w/username and password $pwd = $ftp->pwd; # get current directory # Now, output HTML page. print <<HTML; Content-type: text/html <HTML> <HEAD> <TITLE>Download Files</TITLE> </HEAD> <BODY> <B>Current working directory:</B> $pwd<BR> Files to download: <P> HTML @entries = $ftp->ls($home); # slurp all entries into an array foreach (@entries) { # now, output links for all files in the ftp area # as links print "<INPUT TYPE=hidden NAME=\"files\" VALUE=\"$_\">\n"; print "<A HREF=\"ftp://$hostname$_\">", "<IMG SRC=\"https://www/icons/f.gif\" border=0>\n"; print " $_</A><BR>\n"; } print <<HTML; </BODY> </HTML> HTML $ftp->quit; # end FTP session
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - FTP Configuration with Net::Netrc
- Content preview·Buy reprint rights for this chapterUnix-based FTP clients use a file called .netrc, which you can configure to automate FTP access to sites you frequently visit. With a properly defined .netrc file, you can simply execute the FTP command to a favorite FTP host and be automatically logged in to the FTP server. Your .netrc file contains one line for each connection you want to be able to make. The following tokens can be specified for each entry:
-
machine
name -
Specifies a remote machine to which you want to autologin:
machine remotehost.com
Instead ofmachine
name, you can specify the single worddefault
to match any machine name. This is usually used for anonymous logins to machines not listed in .netrc. -
login
name -
If present, identifies the user who logs in to the remote machine, where name is the login name.
-
password
passwd -
If present, gives the password for the user. The autologin process uses the specified password if the remote server requires one.
-
account
acctpw -
If present, gives an additional password for the user. The autologin process uses this password if the remote server requires one.
-
macdef
name
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Chapter 17: The LWP Library
- Content preview·Buy reprint rights for this chapterLWP, the library for web access in Perl, is a bundle of modules that provide a consistent, object-oriented approach to creating web applications. The library, downloaded as the single file named libwww-perl, contains the following classes:
- File
-
Parses directory listings.
- Font
-
Handles Adobe Font Metrics.
- HTML
-
Parses HTML files and converts them to printable or other forms.
- HTTP
-
Provides client requests, server responses, and protocol implementation.
- LWP
-
The core of all web client programs. It creates network connections and manages the communication and transactions between client and server.
- URI
-
Creates, parses, and translates URLs.
- WWW
-
Implements standards used for robots (automatic client programs).
Each module provides different building blocks that make up a whole web transaction—from connection, to request, to response and returned data. Each part is encapsulated by an object to give a standard interface to every web program you write. The following section gives an overview of how LWP works to create a web client.Any web transaction requires an application that can establish a TCP/IP network connection and send and receive messages using the appropriate protocol (usually HTTP). TCP/IP connections are established using sockets, and messages are exchanged via socket filehandles. See Chapter 13, for information on how to manually create socket applications. LWP provides an object for this application with LWP::UserAgent for clients; HTTP::Daemon provides a server object. The UserAgent object acts as the browser: it connects to a server, sends requests, receives responses, and manages the received data. This is how you create a UserAgent object:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - LWP Overview
- Content preview·Buy reprint rights for this chapterAny web transaction requires an application that can establish a TCP/IP network connection and send and receive messages using the appropriate protocol (usually HTTP). TCP/IP connections are established using sockets, and messages are exchanged via socket filehandles. See Chapter 13, for information on how to manually create socket applications. LWP provides an object for this application with LWP::UserAgent for clients; HTTP::Daemon provides a server object. The UserAgent object acts as the browser: it connects to a server, sends requests, receives responses, and manages the received data. This is how you create a UserAgent object:
use LWP::UserAgent; $ua = new LWP::UserAgent;
The UserAgent now needs to send a message to a server requesting a URL (Universal Resource Locator) using therequest
method.request
forms an HTTP request from the object given as its argument. This request object is created by HTTP::Request.An HTTP request message contains three elements. The first line of a message always contains an HTTP command called a method, a Universal Resource Identifier (URI), which identifies the file or resource the client is querying, and the HTTP version number. The following lines of a client request contain header information, which provides information about the client and any data it is sending the server. The third part of a client request is the entity body, which is data being sent to the server (for the POST method). The following is a sample HTTP request:GET /index.html HTTP/1.0 User-Agent: Mozilla/1.1N (Macintosh; I; 68K) Accept: */* Accept: image/gif Accept: image/jpeg
LWP::UserAgent->request
forms this message from an HTTP::Request object. A request object requires a method for the first argument. The GET method asks for a file, while the POST method supplies information such as form data to a server application. There are other methods, but these two are most commonly used.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The LWP Modules
- Content preview·Buy reprint rights for this chapterThe LWP modules provide the core of functionality for web programming in Perl. It contains the foundations for networking applications, protocol implementations, media type definitions, and debugging ability.The modules LWP::Simple and LWP::UserAgent define client applications that implement network connections, send requests, and receive response data from servers. LWP::RobotUA is another client application that is used to build automated web searchers following a specified set of guidelines.LWP::UserAgent is the primary module used in applications built with LWP. With it, you can build your own robust web client. It is also the base class for the Simple and RobotUA modules. These two modules provide a specialized set of functions for creating clients.Additional LWP modules provide the building blocks required for web communications, but you often don't need to use them directly in your applications. LWP::Protocol implements the actual socket connections with the appropriate protocol. The most common protocol is HTTP, but mail protocols (like SMTP), FTP for file transfers, and others can be used across networks.LWP::MediaTypes implements the MIME definitions for media type identification and mapping to file extensions. The LWP::Debug module provides functions to help you debug your LWP applications.The following sections describe the RobotUA, Simple, and UserAgent modules of LWP.The Robot User Agent (LWP::RobotUA) is a subclass of LWP::UserAgent, and is used to create robot client applications. A robot application requests resources in an automated fashion. Robots perform such activities as searching, mirroring, and surveying. Some robots collect statistics, while others wander the Web and summarize their findings for a search engine.The LWP::RobotUA module defines methods to help program robot applications and observes the Robot Exclusion Standards, which web server administrators can define on their web site to keep robots away from certain (or all) areas of the site.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The HTTP Modules
- Content preview·Buy reprint rights for this chapterThe HTTP modules implement an interface to the HTTP messaging protocol used in web transactions. Its most useful modules are HTTP::Request and HTTP::Response, which create objects for client requests and server responses. Other modules provide means for manipulating headers, interpreting server response codes, managing cookies, converting date formats, and creating basic server applications.Client applications created with LWP::UserAgent use HTTP::Request objects to create and send requests to servers. The information returned from a server is saved as an HTTP::Response object. Both of these objects are subclasses of HTTP::Message, which provides general methods of creating and modifying HTTP messages. The header information included in HTTP messages can be represented by objects of the HTTP::Headers class.HTTP::Status includes functions to classify response codes into the categories of informational, successful, redirection, error, client error, or server error. It also exports symbolic aliases of HTTP response codes; one could refer to the status code of 200 as RC_OK and refer to 404 as RC_NOT_FOUND.The HTTP::Date module converts date strings from and to machine time. The HTTP::Daemon module can be used to create webserver applications, utilizing the functionality of the rest of the LWP modules to communicate with clients.This module summarizes a web client's request. For a simple GET request, you define an object with the GET method and assign a URL to apply it to. Basic headers would be filled in automatically by LWP. For a POST or PUT request, you might want to specify a custom HTTP::Headers object for the request, or use the contents of a file for an entity body. Since HTTP::Request inherits everything in HTTP::Message, you can use the header and entity body manipulation methods from HTTP::Message in HTTP::Request objects.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The HTML Module
- Content preview·Buy reprint rights for this chapterThe HTML modules provide an interface to parse HTML documents. After you parse the document, you can print or display it according to the markup tags, or you can extract specific information such as hyperlinks.The HTML::Parser module provides the base class for the usable HTML modules. It provides methods for reading in HTML text from either a string or a file and then separating out the syntactic structures and data. As a base class, Parser does virtually nothing on its own. The other modules call it internally and override its empty methods for their own purposes. However, the HTML::Parser class is useful to you if you want to write your own classes for parsing and formatting HTML.HTML::TreeBuilder is a class that parses HTML into a syntax tree. In a syntax tree, each element of the HTML, such as container elements with beginning and end tags, is stored relative to other elements. This preserves the nested structure and behavior of HTML and its hierarchy.A syntax tree of the TreeBuilder class is formed of connected nodes that represent each element of the HTML document. These nodes are saved as objects from the HTML::Element class. An HTML::Element object stores all the information from an HTML tag: the start tag, end tag, attributes, plain text, and pointers to any nested elements.The remaining classes of the HTML modules use the syntax trees and its nodes of element objects to output useful information from the HTML documents. The format classes, such as HTML::FormatText and HTML::FormatPS, allow you to produce text and PostScript from HTML. The HTML::LinkExtor class extracts all of the links from a document. Additional modules provide means for replacing HTML character entities and implementing HTML tags as subroutines.This module implements the base class for the other HTML modules. A parser object is created with the
new
constructor:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - The URI Module
- Content preview·Buy reprint rights for this chapterThe URI module contains functions and modules to specify and convert URIs. (URLs are a type of URI.) There are three URI modules: URL, Escape, and Heuristic. Of primary importance to many LWP applications is the URI::URL class, which creates the objects used by LWP::UserAgent to determine protocols, server locations, and resource names.The URI::Escape module replaces unsafe characters in URL strings with their appropriate escape sequences. URI::Heuristic provides convenience methods for creating proper URLs out of short strings and incomplete addresses.This module escapes or unescapes "unsafe" characters within a URL string. Unsafe characters in URLs are described by RFC 1738. Before you form URI::URL objects and use that class's methods, you should make sure your strings are properly escaped. This module does not create its own objects; it exports the following functions:uri_escapeuri_escape uri, [regexp]DescriptionGiven a URI as the first parameter, returns the equivalent URI with certain characters replaced with % followed by two hexadecimal digits. The first parameter can be a text string, like "https://www.oreilly.com", or an object of type URI::URL. When invoked without a second parameter,
uri_escape
escapes characters specified by RFC 1738. Otherwise, you can pass in a regular expression (in the context of[ ]
) of characters to escape as the second parameter. For example:$escaped_uri = uri_escape($uri, 'aeiou')
This code escapes all lowercase vowels in$uri
and returns the escaped version.uri_unescapeAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 18: Perl/Tk
- Content preview·Buy reprint rights for this chapterPerl/Tk is an extension for writing Perl programs with a Graphical User Interface (GUI) on both Unix and Windows 95/NT. Tk was originally developed as an extension to the Tcl language, for use with the X Window System on Unix. With its port to Perl, Tk gives Perl programmers the same control over the graphical desktop that Tcl programmers have taken for granted.The Tk extension makes it easy to draw a window, put widgets into it (such as buttons, checkboxes, entry fields, menus, etc.) and have them perform certain actions based on user input. A simple "Hello World" program would look like this:
#!/usr/bin/perl -w use Tk; my $mw = MainWindow->new; $mw->Button(-text => "Hello World!", -command =>sub{exit})->pack; MainLoop;
When you run it, it would look like Figure 18.1.Figure 18.1: A simple Perl/Tk programPushing the "Hello World!" button exits the program, and your window disappears.Let's walk through these few lines of code. After calling the Perl interpreter, the program calls the Tk module. Then it proceeds to build a generic, standard window (MainWindow
) to act as a parent for any other widgets you create. Line 4 of the program creates a button and displays it using thepack
geometry manager. It also gives the button something to do when pushed (in this case, exit the program).The very last line tells the program to "go do it."MainLoop
starts the event handler for the graphical interface, and the program draws any windows until it reaches theMainLoop
statement. Everything up to that point is preparation; until you reach theMainLoop
statement, the program simply prepares its windows and defines what to do when certain events happen (such as a mouse click on the "Hello World!" button). Nothing is drawn until theMainLoop
statement is reached.Widgets in Perl/Tk are created withAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Widgets
- Content preview·Buy reprint rights for this chapterWidgets in Perl/Tk are created with widget creation commands, which include
Button
,Canvas
,CheckButton
,Entry
,Frame
,Label
,Listbox
,Menu
,Menubutton
,Message
,Radiobutton
,Scale
,Scrollbar
,Text
, andToplevel
.Positioning widgets is done with geometry managers. In the "Hello World" example shown earlier, thepack
command is the geometry manager. Geometry managers determine where in the window (or frame) the widget will sit. We'll talk more about the Perl/Tk geometry managers later in this chapter.Widgets can be configured, queried, or manipulated via various widget methods. For example, all widgets support theconfigure
widget method for changing widget properties after the widget is created. In addition, most widgets have specialized methods associated with them for manipulating the widget as needed throughout the program. For example, widgets that scroll support thexview
andyview
methods for determining the viewable portion of the content when the scrollbar is moved. The Entry and Text widgets have methods for inserting and deleting values. The Canvas widget has a whole series of methods for drawing shapes and inserting text into the canvas. And so on.Widget methods are listed in the discussion of each widget later in this chapter. However, since all widgets support theconfigure
andcget
methods, we're going to cover them now.Section 18.1.1.1: The configure method
Theconfigure
method can be used to set and retrieve widget configuration values. For example, to change the width of a button:$button->configure(-width => 100);
To get the value for a current widget, just supply it without a value:$button->configure(-width);
The result is an array of scalars; the values you care about are the last two, which represent the default value and its current value, respectively.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Geometry Managers
- Content preview·Buy reprint rights for this chapterCreating widgets and determining how to display them are done with separate commands. You can create a widget with one of the widget creation methods (such as
Button
,Canvas
, etc.), but you display them using a geometry manager. The three geometry managers arepack
,grid
, andplace
.pack
is by far the most commonly used.You can either pack a widget as you create it, or you can create the widget object and pack it separately. For example, the previous "Hello World!" example might have read:#!/usr/bin/perl -w use Tk; my $mw = MainWindow->new; $button = $mw->Button(-text => "Hello World!", -command =>sub{exit}); $button->pack; MainLoop;
With thepack
geometry manager, widgets cannot overlap or cover each other, either partially or completely. Once a widget is packed into a window, the next widget is packed in the remaining space around it.pack
sets up an "allocation rectangle" for each widget, determined by the dimensions of the parent window and the positioning of the widgets already packed into it. This means that the order in which you pack your widgets is very important.By default,pack
places widgets at the top center of the allocation rectangle. However, you can use options topack
to control where a widget is placed and how much padding is placed around it. Options forpack
are:-
-side =>
side -
Puts the widget against the specified side of the window. Values for side are
'left'
,'right'
,'top'
, and'bottom'
. The default is'top'
. -
-fill =>
direction -
Causes the widget to fill the allocation rectangle in the specified direction. Values for
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Common Widget Configuration Options
- Content preview·Buy reprint rights for this chapterIn the remainder of this chapter, we'll be discussing each widget: the command used to create each widget, the options used to configure them, and the methods for manipulating them.You'll find that there are many, many configuration options that are shared by multiple widgets. We could list them individually for each widget, but in the interest of saving a tree or two, we're instead going to list the shared options up front, rather than repeating them over and over. That way we can concentrate on the options that are crucial to the behavior of each particular widget, and save the reader from being lost in a sea of options.The following options are supported by the widgets noted:
-
-activebackground =>
color -
Sets the background color when the mouse cursor is over the widget.Applicable widgets: Button, Checkbutton, Menu, Menubutton, Optionmenu, Radiobutton, Scale, Scrollbar
-
-activeforeground =>
color -
Sets the text color when the mouse cursor is over the widget. Applicable widgets: Button, Checkbutton, Menu, Menubutton, Optionmenu, Radiobutton
-
-anchor =>
position -
Causes the text to stick to that position in the widget. Values for position are
'n'
,'ne'
,'e'
,'se'
,'s'
,'sw'
,'w'
,'nw'
, and'center'
. Applicable widgets: Button, Checkbutton, Label, Menubutton, Optionmenu, Radiobutton -
-background =>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Button Widget
- Content preview·Buy reprint rights for this chapterCreate a simple button with the
Button
method:$parentwidget->Button (options)
The standard configuration options that apply toButton
are:-activebackground
,-activeforeground
,-anchor
,-background
,-bg
,-bitmap
,-borderwidth
,-bd
,-cursor
,-disabledforeground
,-font
,-foreground
,-fg
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-image
,-justify
,-padx
,-pady
,-relief
,-state
,-takefocus
,-underline
,-width
, and-wraplength
.Other options are:-
-command =>
callback -
Pointer to a function that will be called when the button is pressed.
-
-text => '
text'
-
Defines the text string displayed on the button. See also
-textvariable
. -
-textvariable =>
\$variable -
Points to the variable containing text to be displayed in the button. Button text will change as $variable does.
In addition toconfigure
andcget
, the following methods can be used forButton
:-
flash
-
Causes the button to flash from the normal to active state colors.
-
invoke
-
Invokes the callback command as if the button were clicked.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Checkbutton Widget
- Content preview·Buy reprint rights for this chapterCreates a checkbutton with the
Checkbutton
command. A checkbutton has an indicator to the left of the label indicating whether the button is selected. The boolean status of the button ("0" or "1", or values as specified by the-onvalue
and-offvalue
options) is stored in the variable specified with the-variable
option.$parentwidget->Checkbutton (options)
The standard configuration options that apply toCheckButton
are:-activebackground
,-activeforeground
,-anchor
,-background
,-bg
,-bitmap
,-borderwidth
,-bd
,-cursor
,-disabledforeground
,-font
,-foreground
,-fg
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-image
,-justify
,-padx
,-pady
,-relief
,-state
,-takefocus
,-underline
,-width
, and-wraplength
.Other options are:-
-command =>
callback -
Pointer to a function that will be called when the checkbutton is pressed.
-
-indicatoron =>
boolean -
Determines whether or not to display the indicator. Default is on (1).
-
-offvalue =>
newvalue -
Specifies the value used when the checkbutton is "off." Must be a scalar. Default is 0.
-
-onvalue =>
newvalue -
Specifies the value used when the checkbutton is "on." Must be a scalar. Default is 1.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Radiobutton Widget
- Content preview·Buy reprint rights for this chapterCreate a radiobutton with the
Radiobutton
method. A radiobutton has an indicator to the left of the label indicating whether the button is selected. It differs from a checkbutton in that only one button may be selected at the same time. Each button in a group of radiobuttons uses the same variable specified with the-variable
option; when selected, the button assigns that variable the value specified by the-value
option.$parentwidget->Radiobutton (options)
The standard configuration options that apply toRadiobutton
are:-activebackground
,-activeforeground
,-anchor
,-background
,-bg
,-bitmap
,-borderwidth
,-bd
,-cursor
,-disabledforeground
,-font
,-foreground
,-fg
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-image
,-justify
,-padx
,-pady
,-relief
,-underline
,-width
, and-wraplength
.Other options are:-
-command =>
callback -
Pointer to a function that will be called when the radiobutton is pressed.
-
-indicatoron =>
boolean -
Determines whether or not to display the indicator. Default is on (1).
-
-selectcolor =>
color -
Color of the indicator when the radiobutton is on.
-
-selectimage =>
imgptr -
Defines the image to be displayed instead of text when the radiobutton is on. Ignored if
-image
is not used.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Label Widget
- Content preview·Buy reprint rights for this chapterCreate a non-interactive label with the
Label
command.$parentwidget->Label (options)
The standard configuration options that apply toLabel
are:-anchor
,-background
,-bg
,-bitmap
,-borderwidth
,-bd
,-cursor
,-font
,-foreground
,-fg
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-image
,-justify
,-padx
,-pady
,-relief
,-takefocus
,-underline
,-width
, and-wraplength
.Other options are:-
-text => '
text'
-
Defines the text string displayed in the label. See also
-textvariable
. -
-textvariable =>
\$variable -
Points to the variable containing text to be displayed in the label. Button text will change as $variable does.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Entry Widget
- Content preview·Buy reprint rights for this chapterCreate an entry widget with the
Entry
method. The value that the user has typed into the widget is stored in the variable pointed to by the-textvariable
option.$parent->Entry (options)
The standard configuration options that apply toEntry
are:-background
,-bg
,-borderwidth
,-bd
,-cursor
,-exportselection
,-font
,-foreground
,-fg
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-insertbackground
,-insertborderwidth
,-insertofftime
,-insertontime
,-insertwidth
,-justify
,-relief
,-selectbackground
,-selectborderwidth
,-selectforeground
,-state
,-takefocus
, and-xscrollcommand
.Other options are:-
-show =>
x -
Defines a character to be displayed in place of actual typed text (for use with passwords).
-
-textvariable =>
\$variable -
Points to the variable containing text to be displayed in the entry widget. Button text will change as $variable does.
In an Entry widget, several indexes are defined to identify positions in the entry text, for use by the methods used for retrieving or manipulating entry text. These indexes are:- n
-
An integer representing a character position, with 0 as the first character in the string.
-
insert
-
The character directly after the insert cursor.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Scrollbar Widget
- Content preview·Buy reprint rights for this chapterCreate a scrollbar with the
Scrollbar
method.$parentwidget->Scrollbar (options)
The standard configuration options that apply toScrollbar
are:-activebackground
,-background
,-bg
,-borderwidth
,-bd
,-cursor
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-relief
,-takefocus
, and-width
.Other options are:-
-activerelief =>
type -
Changes how active elements (arrow1, arrow2, and the slider) in the scrollbar are drawn. Values for type are
'flat'
,'groove'
,'raised'
,'ridge'
, and'sunken'
. The default is'raised'
. -
-command =>
callback -
Pointer to a function that will be called when the scrollbar is clicked on.
-
-elementborderwidth =>
amount -
The width of the borders of the arrow1, arrow2, and slider elements.
-
-jump =>
boolean -
Determines whether the scrollbar will jump scroll. Default is 0 (jump scroll disabled).
-
-orient =>
orientation -
Determines the orientation of the scrollbar. Possible orientations are
'horizontal'
and'vertical'
(default).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Listbox Widget
- Content preview·Buy reprint rights for this chapterCreate a listbox with the
Listbox
method. You can then insert items into the listbox using theinsert
method.$parentwidget->Listbox (options)
The standard configuration options that apply toListbox
are:-background
,-bg
,-borderwidth
,-bd
,-cursor
,-exportselection
,-font
,-foreground
,-fg
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-relief
,-selectbackground
,-selectborderwidth
,-selectforeground
,-takefocus
,-width
,-xscrollcommand
, and-yscrollcommand
.Other options are:-
-selectmode =>
mode -
Determines how many items can be selected at once, as well as key/mouse bindings. mode can be any of:
-
-setgrid =>
boolean -
Turns on gridding for the listbox. If the widget is resized, only complete lines and characters are displayed. Default is 0 (off).
In a Listbox widget, several indexes are defined to identify positions in the listbox, for use by the methods used for retrieving or manipulating listbox entries. These indexes are:- n
-
An integer representing a position in the list, with 0 as the first item.
-
active
-
The item with the keyboard focus.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Text Widget
- Content preview·Buy reprint rights for this chapterCreate a text widget with the
Text
method:$parentwidget->Text ( options)
The standard configuration options that apply toText
are:-background
,-bg
,-borderwidth
,-bd
,-cursor
,-exportselection
,-font
,-foreground
,-fg
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-insertbackground
,-insertborderwidth
,-insertofftime
,-insertontime
,-insertwidth
,-padx
,-pady
,-relief
,-selectbackground
,-selectborderwidth
,-selectforeground
,-state
,-takefocus
,-width
,-xscrollcommand
, and-yscrollcommand
.Other options are:-
-setgrid =>
boolean -
Turns on gridding for the text widget. Default is 0 (off).
-
-spacing1 =>
amount -
Defines the amount of space left on the top of a line of text that starts on its own line. Default is 0.
-
-spacing2 =>
amount -
Defines the amount of space left on the top of a line of text after it has been automatically wrapped by the text widget. Default is 0.
-
-spacing3 =>
amount -
Defines the amount of space left after a line of text that has been ended by "
\n
". Default is 0. -
-tabs =>
list -
Specifies a list of tab stops to use in the text widget. Default is undefined (no tab stops).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Canvas Widget
- Content preview·Buy reprint rights for this chapterCreate a canvas for drawing with the
Canvas
method. The Canvas widget uses a coordinate system with the x coordinate increasing as you move right, and the y coordinate increasing as you move down (i.e., the y coordinate is mathematically upside-down). The x and y coordinates are specified in pixels by default.$parentwidget->Canvas ( options)
The standard configuration options that apply toCanvas
are:-background
,-borderwidth
,-cursor
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-insertbackground
,-insertborderwidth
,-insertofftime
,-insertontime
,-insertwidth
,-relief
,-selectbackground
,-selectborderwidth
,-selectforeground
,-takefocus
,-width
,-xscrollcommand
, and-yscrollcommand
.Other options are:-
-closeenough =>
amount -
The distance considered "close enough" to an item to be judged to be within it. Default is 1 pixel.
-
-confine =>
boolean -
Whether to limit the canvas to the scroll region. Default is 1.
-
-scrollregion =>
[ x, y, w, h ] -
Sets the region that the user is allowed to scroll. The option is a list reference that conveniently corresponds to the return value of the
bbox
method. -
-xscrollincrement =>
amount -
The distance to use for scrolling in the x direction.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Scale Widget
- Content preview·Buy reprint rights for this chapterCreate a "slider" widget representing a numeric value with the
Scale
method.$parent->Scale(options);
The standard configuration options that apply toScale
are:-activebackground
,-background
,-bg
,-borderwidth
,-bw
,-cursor
,-font
,-foreground
,-fg
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-relief
,-state
,-takefocus
, and-width
.Other options are:-
-bigincrement =>
amount -
The amount to change the slider when using large increments. Default is 0, which means 1/10 of the scale.
-
-command =>
callback -
Pointer to a function that will be called for every incremental change in the slider.
-
-digits =>
amount -
The number of digits to keep when converting from a number to a string.
-
-from =>
n -
Low end of the scale (default = 0).
-
-label =>
string -
The string to use as a label for the slider.
-
-length =>
amount -
The length of the slider.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Menubutton Widget
- Content preview·Buy reprint rights for this chapterCreate a menubutton with the
Menubutton
method. For example:$mainwindow->Menubutton(-text => "File", -menuitems => [ [ 'command' => "New", "-command" => \&newfile, "-underline" => 0 ], [ 'command' => "Open", "-command" => \&openfile, "-underline" => 0 ], "-", [ 'command' => "Save", "-command" => \&savefile, "-underline" => 0 ], [ 'command' => "SaveAs", "-command" => \&saveasfile, "-underline" => 4 ] ] );
The-menuitems
option takes a list of lists describing the menu items. For each menu item, an embedded anonymous list describes the type of menu item, the label to use, and the action to take when it is selected along with any other options desired to configure the menu item. In this example, each of the menu items is the'command'
type, and we use the-command
option for each item to point to the callback to execute when the menu item is selected. We also use the-underline
option to enable the user to select a menu item using keystrokes. (The\[quotedbl]-"
represents a separator between menu items.)In addition to'command'
, other types of menus are:-
'cascade'
-
Embeds a cascade menu.
-
'checkbutton'
-
Treats the menu item as a checkbutton.
-
'command'
-
Executes a callback.
-
'radiobutton'
-
Treats the menu item as a radiobutton.
You can configure both the menu itself and the individual menu items. The configuration options that apply toAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Menu Widget
- Content preview·Buy reprint rights for this chapterCreate a menu with the
Menu
method, to be displayed later with thepost
method.$menu = $parent->Menu(options)
The standard configuration options that apply toMenu
are:-activebackground
,-activeforeground
,-background
,-bg
,-borderwidth
,-bw
,-cursor
,-disabledforeground
,-font
,-foreground
,-fg
,-relief
, and-takefocus
.Other options are:-
-activeborderwidth =>
amount -
Sets the width of the edges for the active menu item.
-
-menuitems =>
list -
Specifies items to create in the menu as a list of lists.
-
-postcommand =>
callback -
The command to invoke before the menu is posted, for example, to update the state of the menu items.
-
-tearoff =>
boolean -
Whether or not to allow the menu to be "torn off." Default is 1.
-
-selectcolor =>
color -
Color of the selection box for checkbuttons or radiobuttons.
Menus have indexes for manipulating individual menu items. They are:- n
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Optionmenu Widget
- Content preview·Buy reprint rights for this chapterUse the
Optionmenu
method to create an option menu, in which the selected item is the value displayed. For example:$mainwindow->OptionMenu(-textvariable => \$platform, -options => [ [ "UNIX", "unix" ], [ "Windows NT", "winnt" ], [ "Macintosh", "mac" ] ]) -> pack;
The-options
argument takes a list of menu items. If the description of the menu items that are displayed are different from the values stored, the menu items are themselves written as two-item lists.The standard configuration options that apply toOptionmenu
are:-activebackground
,-activeforeground
,-background
,-bg
,-bitmap
,-borderwidth
,-bw
,-cursor
,-disabledforeground
,-font
,-foreground
,-fg
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-image
,-justify
,-relief
,-state
,-takefocus
,-underline
,-width
, and-wraplength
.Other options are:-
-command =>
callback -
The command to execute when a selection is made, with its arguments being the values of the
-textvariable
and-variable
options. -
-indicatoron =>
boolean -
Determines whether or not to display an indicator.
-
-menu =>
$menu -
Displays the menu associated with $menu.
-
-options =>
list -
Lists the menu options, as described above.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Frame Widget
- Content preview·Buy reprint rights for this chapterCreate a frame for enclosing other widgets using the
Frame
method. For example:$parent->Frame( options )
The standard configuration options that apply toFrame
are:-background
,-bg
,-borderwidth
,-bw
,-cursor
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-relief
,-takefocus
, and-width
.Other options are:-
-class =>
name -
The class associated with the frame.
-
-colormap =>
\$window -
Specifies another window to share the colormap with. You can point to another window or use the value "new" to specify a new colormap. Default is
undef
. -
-label =>
string -
The string to use as a label for the frame.
- "
-labelPack
-
Specifies options for the
pack
command. -
-labelVariable =>
\$variable -
Specifies a variable containing the text for the label.
-
-visual =>
type n -
For the X Window System, changes the depth of colors.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- The Toplevel Widget
- Content preview·Buy reprint rights for this chapterCreate a toplevel widget, displayed independently from the main window with the same decoration as the window system, using the
Toplevel
method.The standard configuration options that apply toToplevel
are:-background
,-bg
,-borderwidth
,-bw
,-cursor
,-height
,-highlightbackground
,-highlightcolor
,-highlightthickness
,-relief
,-takefocus
, and-width
.Other options are:-
-class =>
name -
The class associated with the toplevel widget.
-
-colormap =>
\$window -
Specifies another window to share the colormap with. You can point to another window or use the value
"new"
to specify a new colormap. Default isundef
. -
-screen =>
screen -
The screen to place the toplevel widget on.
-
-visual =>
type n -
For the X Window System, changes the depth of colors.
In addition tocget
andconfigure
, the following methods are supported by the Toplevel widget. Note that since the MainWindow is a Toplevel widget, each of these methods applies to the MainWindow as well.-
aspect
-
Returns the constraints to the aspect of the window. The four-item list returned corresponds to the minimum width, the minimum height, the maximum width, and the maximum height.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Chapter 19: Win32 Modules and Extensions
- Content preview·Buy reprint rights for this chapterIf you use Perl on a Win32 system, a number of extension modules are available to provide Windows-specific functionality. Extension modules consist of a regular module written in Perl and a library written in C or C++ that can implement native Windows calls. The core of available modules is bundled together as lib-win32 on CPAN, and with ActivePerl, Activestate's version of Perl for Win32. They provide such functionality as managing Windows processes, NT user administration, registry modification, and OLE automation.The Win32 modules were originally written for Windows NT systems, so much of the functionality of the Win32 library is only applicable to Perl running on Windows NT. Many modules check to see which system they are on before installing. Many of the NT-specific modules such as NetAdmin and EventLog do not install at all on Windows 95. Modules like Registry do their best to work on both systems, despite the differences in their registries.This chapter covers most of the modules and extensions included in lib-win32 and distributed with ActivePerl. Additional Windows modules are available at CPAN.The following modules are described in this chapter:
- Win32::Clipboard
-
Provide Windows clipboard interaction
- Win32::Console
-
Provide Windows console interaction
- Win32::ChangeNotification
-
Create and use ChangeNotification objects
- Win32::EventLog
-
Read from and write to the Windows NT event log
- Win32::File
-
Manage file attributes (read-only, system, hidden…)
- Win32::FileSecurity
-
Manage ACLs in Perl
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Clipboard
- Content preview·Buy reprint rights for this chapterThe Win32::Clipboard module allows you to manipulate the Windows clipboard. You can use the clipboard as an object with the following syntax:
$clip = Win32::Clipboard();
This functions as an implicit constructor. If you include a text string as an argument, that text will be placed on the clipboard. You can just use the package-qualified method names instead of the object syntax, since the clipboard is a single entity.$text = Win32::Clipboard::Get(); Win32::Clipboard::Set("blah blah blah"); Win32::Clipboard::Empty();
Alternatively, you can use the clipboard as an object with this syntax:$Clip = Win32::Clipboard(); $text = $Clip->Get(); $Clip->Set("blah blah blah"); $Clip->Empty();
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Console
- Content preview·Buy reprint rights for this chapterWin32::Console implements the Win32 console and character mode functions. They give you full control on the console input and output, including: support of off-screen console buffers (e.g., multiple screen pages); reading and writing of characters, attributes, and whole portions of the screen; and complete processing of keyboard and mouse events.The
new
constructor is used to create a console object. It can take two forms:$con = Win32::Console->new(standard_handle); $con = Win32::Console->new(accessmode, sharemode);
The first form creates a handle to a standard channel. standard_handle can be one ofSTD_OUTPUT_HANDLE
,STD_ERROR_HANDLE
, orSTD_INPUT_HANDLE
.The second form creates a console screen buffer in memory, which you can access for reading and writing as a normal console, and then redirect on the standard output (the screen) withDisplay
. In this case, you can specify accessmode to beGENERIC_READ
,GENERIC_WRITE
, or both, determining the permissions you will have on the created buffer.sharemode affects the way the console can be shared. It can be specified either asFILE_SHARE_READ
,FILE_SHARE_WRITE
, or both. If you don't specify any of those parameters, all four flags will be used.Methods supported by the Win32::Console module are:Alloc$cons ->AllocDescriptionAllocates a new console for the process. Returnsundef
on error or a nonzero value on success. A process cannot be associated with more than one console, so this method will fail if there is already an allocated console. UseFree
to detach the process from the console, and then callAlloc
to create a new console.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::ChangeNotification
- Content preview·Buy reprint rights for this chapterThis module provides access to Win32 change-notification objects, letting you monitor events relating to files and directory trees. The constructor for this class is
new
, which creates a ChangeNotification object for a specified directory and indicates how it should be monitored:$ntfy = Win32::ChangeNotification->new(directory, subtree, filter);
The function returns a reference to the object as$ntfy
. directory is the pathname of the directory to monitor. subtree is a Boolean value that, if true, forces the object to monitor all subdirectories of the object's path. The filter parameter indicates what type of events will trigger a notification. It can be one of the following string values:Value Description ATTRIBUTES Any attribute change DIR_NAME Any directory name change FILE_NAME Any filename change (creating/deleting/renaming) LAST_WRITE Any change to a file's last write time SECURITY Any security descriptor change SIZE Any change in a file's size The following methods are used on notification objects created bynew
:close$ntfy ->close()DescriptionStops the monitoring done by the notification object and destroys the object. This happens automatically when the program exits.reset$ntfy ->reset()DescriptionResets the object to begin monitoring again after a change has occurred.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Eventlog
- Content preview·Buy reprint rights for this chapterThis module makes the Windows NT event log accessible to your Perl programs. It allows you to create new records, read records, and create backup logfiles. The
new
constructor opens a server's event log as an object.$log = Win32::EventLog->new(source, [server]);
This function opens an event log and returns an object reference. source specifies the name of the source event, and server specifies the name of the server (local
is assumed if no server name is given).Many of the methods for this module require a reference to an empty variable as an argument. This is where the return value of the method will be placed, whether it is a hash or a scalar. The following methods can be used on event log objects:Backup$log->Backup(filename)DescriptionSaves the current open event log to a file named by filename.Read$log->Read(flags, offset, \%eventinfo)DescriptionReads an entry from the event log and returns the information in the eventinfo hash. offset specifies the record number you want to start at in the log. flags sets options for how you want to read the log, which can be any combination of the following:-
EVENTLOG_FORWARDS_READ
-
Eventlog is read in forward chronological order.
-
EVENTLOG_BACKWARDS_READ
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Win32::File
- Content preview·Buy reprint rights for this chapterThe Win32::File module allows you to view or set the attributes for files. There are two functions that allow you to do this, which must be explicitly imported to your namespace:
use Win32::File qw/GetAttributes SetAttributes/;
The constant values for the attributes are exported by default.-
GetAttributes
(filename, \$atts) -
Returns the attribute settings for file filename and saves them as the variable referenced by $atts, which will contain an ORed combination of one or more of the following values:
ARCHIVE DIRECTORY HIDDEN NORMAL READONLY SYSTEM
-
SetAttributes
(filename, atts) -
Set the attributes for the file filename to the values contained in atts. The attributes are given as an ORed combination of one or more of the attribute values shown above.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Win32::FileSecurity
- Content preview·Buy reprint rights for this chapterThe Win32::FileSecurity module allows you to work with NT File System (NTFS) file permissions. File permissions are stored as Discretionary Access Control Lists (DACLs) for each file or directory. These lists contain a bitmask specifying the permission rights for users on the file or directory. This module implements a DACL as a permissions hash in which each key is a username and the value is the bitmask for the permissions.The FileSecurity module exports the following constants to describe user permissions:
ACCESS_SYSTEM_SECURITY READ or R CHANGE or C SPECIFIC_RIGHTS_ALL DELETE STANDARD_RIGHTS_ALL FULL or F STANDARD_RIGHTS_EXECUTE GENERIC_ALL STANDARD_RIGHTS_READ GENERIC_EXECUTE STANDARD_RIGHTS_REQUIRED GENERIC_READ STANDARD_RIGHTS_WRITE GENERIC_WRITE SYNCHRONIZE MAXIMUM_ALLOWED WRITE_DAC READ_CONTROL WRITE_OWNER
Using theconstant
function on one of these constants gives its value, and bitmasks or multiple permissions settings can be made by supplying a list of these constants to theMakeMask
function.The functions exported by the Win32::FileSecurity module are:constantconstant (name $val)DescriptionTakes the name of a permission constant and saves its value in the variable val.EnumerateRightsEnumerateRights (mask, \@rights)DescriptionTakes a permissions bitmask (as returned byMakeMask
orconstant
) and saves the corresponding list of string constants in rightsAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Internet
- Content preview·Buy reprint rights for this chapterThe Win32::Internet extension implements the Win32 Internet APIs (found in WININET.DLL), providing support for HTTP, FTP, and Gopher connections.All types of connections start as a basic Internet connection that must be opened with the following command:
use Win32::Internet; $Connection = Win32::Internet->new();
This creates an Internet object in Perl on which you use the functions provided in this module to create more specific connection objects. The objects and functions that create them are:-
Internet connections (the main object, with
new
) -
URLs (with
OpenURL
) -
FTP sessions (with
FTP
) -
HTTP sessions (with
HTTP
) -
HTTP requests (with
OpenRequest
)
This module provides different levels of implementation of the Win32 Internet functions. Some routines use several Win32 API functions to perform a complex task in a single call; they are simpler to use, but less powerful. Other functions implement nothing more and nothing less than the corresponding API function, so you can use all of their power, but with some additional programming steps.For example, the functionFetchURL
fetches the contents of any HTTP, FTP, or Gopher URL with a simple command:$inet = new Win32::Internet(); $file = $inet->FetchURL("https://www.yahoo.com");
You can achieve the same result with this series of commands, which is whatFetchURL
actually does:$inet = new Win32::Internet(); $url = $inet->OpenURL("https://www.yahoo.com"); $file = $url->ReadFile(); $url->Close();
The methods described in this section are used on Internet connection objects created withnew
:$inet = Win32::Internet->new();
You can supplynew
with an optional list of arguments (or a reference to a hash containing them) that looks like this:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Win32::IPC
- Content preview·Buy reprint rights for this chapterThe Win32::IPC module provides synchronization for multiple objects created from the Semaphore, Mutex, Process, and ChangeNotify classes. This
wait
method of this class is inherited by objects of the preceding modules, as well as the functionswait_all
andwait_any
. You should not need to call Win32::IPC directly.-
$obj->wait([timeout])
-
This method is used on any synchronization object. It waits for the object to become signaled. It returns 1 if the object is signaled, -1 if the object is an abandoned mutex, 0 if the call times out, and
undef
on error. timeout is the time to wait (in milliseconds). If no timeout is specified, the method waits indefinitely.
Win32::IPC also defines the two functionswait_all
andwait_any
:-
wait_all(@objects, [timeout])
-
Waits for all the synchronization objects contained in @objects to be signaled. The optional timeout parameter is the same as described for
wait
. The return value will be an integer that identifies the last object to be signaled (the nth object in the list, starting from 1). A negative integer (-n) indicates that the nth object was an abandoned mutex. A return of 0 means that the function timed out; andundef
is returned on error. -
wait_any(@objects, [timeout])
-
Waits for at least one of the objects contained in @objects to be signaled. Return values are the same as for
wait_all
, above, indicating which object signaled.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- Win32::Mutex
- Content preview·Buy reprint rights for this chapterThis module provides access to Win32 mutex objects, which control access to common resources. The
new
constructor creates the mutex and determines its initial availability. It has the following syntax:$mut = Win32::Mutex->new(init, [name]);
The first argument determines the initial status of the mutex. If init is non-zero, the calling process has immediate ownership of the mutex object. A zero value means that the mutex is available. The second argument assigns a name to the mutex that allows this object to be referenced by others via theopen
function.Another object constructor for Win32::Mutex isopen
:$mut = Win32::Mutex->open(name);
This call creates a new mutex object to access an existing mutex identified by name.The following methods can be used on Win32::Mutex objects:release$mut ->Release()DescriptionReleases ownership of the mutex from the calling process, allowing anyone waiting on the mutex to take ownership.wait$mut ->wait([timeout])DescriptionThe Win32::IPC method inherited by this module. Makes the calling process wait for ownership of the mutex object for the number of milliseconds specified by timeout. If the mutex doesn't become available before the timeout, the call returns 0.Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::NetAdmin
- Content preview·Buy reprint rights for this chapterThe Win32::NetAdmin module provides extensive functionality for administering users and groups on Windows NT servers. This module does not implement an object interface for administration; it exports several functions that execute administrative commands. (This module does not load on Windows 95 systems.)The following functions are provided by the Win32::NetAdmin module. The server argument of each function is optional; however, a placeholder for the argument must be used if you don't supply a name. An empty string (
"carview.php?tsp="
) will work, indicating that the local machine is to be used.GetDomainControllerGetDomainController (server, domain, $name)DescriptionReturns the name of the domain controller for the specified server and domain to the variable $name.UserCreateUserCreate (server, username, password, passwordage, privilege, homedir, comment, flags, scriptpath)DescriptionCreates a new user with the specified settings:- server
-
Name of the server
- username
-
Name of new user
- password
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::NetResource
- Content preview·Buy reprint rights for this chapterThe Win32::NetResource module allows you to manage shared resources on a network, such as printers, disks, etc. Two data structures are used to provide or store information for many of the NetResource functions. The first is the
share_info
hash. This hash contains parameters for setting up a share, using the following structure:%share_info = ( netname => "name of share", type => "type of share", remark => "a string comment", permissions => "permissions value", maxusers => "the max number of users", current-users => "the current number of users", path => "the path of the share", passwd => "password, if required" );
Anetresource
data structure contains information about the shared resource or device. It has the following structure:%netresource = ( 'Scope' => "Scope of a resource connection (see table below for values)", 'Type' => "The type of resource (see table below)", 'DisplayType' => "How the resource should be displayed (see table below)", 'Usage' => "How the resource should be used", 'LocalName' => "Name of the local device the resource is connected to", 'RemoteName' => "Network name of the resource", 'Comment' => "Comment string", 'Provider' => "Provider of the resource" );
The first three elements of thenetresource
hash contain values described in the following tables. TheScope
value can be one of the following:RESOURCE_CONNECTED Resource is already connected. RESOURCE_REMEMBERED Resource is reconnected each time the user logs on. RESOURCE_GLOBALNET Resource is available to the entire network.
TheType
element takes one of the following values:RESOURCETYPE_ANY All resources RESOURCETYPE_DISK Disk resources RESOURCETYPE_PRINT Print resources
TheDisplay
element can be one of these values:Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Process
- Content preview·Buy reprint rights for this chapterThis module provides access to extended Win32 process creation and management abilities. Process objects are created with the
Create
method (the constructor). Additional methods can be used on objects to kill, suspend, resume, and set the priorities of processes.TheCreate
constructor has the following syntax:Win32::Process->Create($Proc, app, cmnd, hndls, opts, dir)
The arguments toCreate
are as follows:- $Proc
-
Name of the reference for the created process object.
- app
-
Full pathname of the executable.
- cmnd
-
Command line for executable.
- hndls
-
Determines handle inheritance. A value of 1 turns on inheritance; a 0 value turns it off.
- opts
-
Sets options to implement when the process is created. The available options for this argument are listed below.
- dir
-
The working directory for the executable.
The process is created by passing the command line in cmnd to the executable named in app. For example, a process object for a text file running in Notepad is created like this:use Win32::Process; Win32::Process->Create($proc, 'C:\\windows\\Notepad.exe', "Notepad perlnut.txt", 1, DETACHED_PROCESS, ".");
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Registry
- Content preview·Buy reprint rights for this chapterThis module provides access to the Windows Registry, the database that stores information about all parts of your system and software. Many operating system and application behaviors are controlled by Registry data. The Win32::Registry module gives you a way to access and update registry information with Perl. (Warning: Always be careful when making changes to the registry. If vital system information gets changed by mistake, your system could become inoperable. Always make certain you have a backup of your registry before you start to make modifications.)The Registry module automatically creates objects for the top-level registry trees. These objects are created in the
main::
namespace, and each key that you open or create is accessed via one of these root objects. The four top-level objects are:$HKEY_CLASSES_ROOT $HKEY_CURRENT_USER $HKEY_LOCAL_MACHINE $HKEY_USERS
If you are outside of the main (default) namespace, you should package declare the keys, i.e.,$main::HKEY_USERS
.TheOpen
method creates new key objects for subtrees or subkeys under another open key object. Initially, a new key is opened from one of the main key objects, for example:use Win32::Registry; $p = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"; $HKEY_LOCAL_MACHINE->Open($p, $CurrVer) || die "Open $!";
This example creates a key object$CurrVer
for theCurrentVersion
key for Windows NT. This key contains several values for the version of the operating system. With the new key open, you can read or change the values it contains (every key has at least one unnamed, default value), or open and create subkeys. TheOpen
method can only create key objects for existing keys.Registry values are represented in Win32::Registry functions by three elements: the name of the value, the data type of the value, and the value itself. There are several different data types for the values. Win32::Registry defines the following constants for these types:REG_SZ String data REG_DWORD Unsigned four-byte integer REG_MULTI_SZ Multiple strings delimited with NULL REG_EXPAND_SZ Strings that expand (e.g., based on environment variables) REG_BINARY Binary data (no particular format is assumed)
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Semaphore
- Content preview·Buy reprint rights for this chapterThe Win32::Semaphore module implements semaphores, synchronizing access to shared resources. The constructor
new
creates a new semaphore object and sets the initial count and the maximum count of the semaphore. The constructor has the following syntax:$sem = Win32::Semaphore->new(init, max, [name]);
The arguments are defined as follows:- init
-
The initial count of the semaphore.
- max
-
The maximum count of the semaphore.
- name
-
A string containing a name of the semaphore.
Theopen
constructor opens an existing semaphore object specified by name:$sem = Win32::Semaphore->open(name);
The following methods can be used on Win32::Semaphore objects:wait$sem ->wait([timeout])DescriptionThe inherited Win32::IPC call. Waits for the semaphore's count to be nonzero, then decrements it. Optional timeout is given in milliseconds.release$sem ->release(inc, [$var])DescriptionReleases a semaphore and increments the count by the amount specified in inc. The last count (before the increment) is returned in theAdditional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Service
- Content preview·Buy reprint rights for this chapterThe Win32::Service module provides a service control interface. It allows you to start, pause, resume, and stop Windows NT system services from Perl scripts.The following functions are exported by this module. The host argument in each function gives the hostname of the machine a service is running (or will run) on. If you supply a null string (
"carview.php?tsp="
), the local machine will be assumed.StartServiceStartService (host, service)DescriptionStarts the named service on the machine host. The specified service must be registered with the Service Control Manager.StopServiceStopService (host, service)DescriptionStops the named service on machine host.GetStatusGetStatus (host, service, \%status)DescriptionReturns the status of service as a hash referenced by status. The keys for this hash are:ServiceType CurrentState ControlsAccepted Win32ExitCode ServiceSpecificExitCode CheckPoint WaitHint
PauseServicePauseService (host, service)DescriptionPauses the named service on machine host (only if the service is able to pause).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32::Shortcut
- Content preview·Buy reprint rights for this chapterThis module allows you to create and manipulate Windows shortcut files (.lnk files) through Perl. The methods and properties of this module apply to shortcut objects created by
new
:use Win32::Shortcut; $link = Win32::Shortcut->new();
This creates the shortcut object$link
, on which you can set properties and save into a file. If you supply a filename as an argument tonew
, the file will be loaded into the shortcut object.The object can also be accessed as if it were a normal hash reference. The following properties (hash keys) are available:$link->{'File'} $link->{'Path'} $link->{'ShortPath'} $link->{'WorkingDirectory'} $link->{'Arguments'} $link->{'Description'} $link->{'ShowCmd'} $link->{'Hotkey'} $link->{'IconLocation'} $link->{'IconNumber'}
See the section on shortcut properties, below, for a description of each property.The following example assumes you have a shortcut file named test.lnk in your current directory. This simple script will tell you where this shortcut points to:use Win32::Shortcut; $link=new Win32::Shortcut(); $link->Load("test.lnk"); print "Shortcut to: $link->{'Path'} $link->{'Arguments'} \n"; $link->Close();
But you can also modify its values:use Win32::Shortcut; $link=new Win32::Shortcut(); $link->Load("test.lnk"); $link->{'Path'}=~s/C:/D:/i; # move the target from C: to D: $link->{'ShowCmd'}=SW_NORMAL; # runs in a normal window
The methods provided by Win32::Shortcut are as follows:Close$link ->Close()DescriptionCloses a shortcut object. It is not strictly required to close the objects you created, since the Win32::Shortcut objects are automatically closed when the program ends (or when you otherwise destroy such an object).Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Win32 Extensions
- Content preview·Buy reprint rights for this chapterIn addition to the modules listed above, Perl for Win32 can use an additional set of functions from the Win32 extension. These functions provide useful tools for some Windows-specific tasks that don't require their own modules. They are exported from the Win32 package with:
use Win32;
Many of these functions do not take arguments, and they return the value (or values) of the requested information, unless otherwise noted.-
Win32::GetLastError()
-
Returns the last error value generated by a call to a Win32 API function.
-
Win32::OLELastError()
-
Returns the last error value generated by a call to a Win32 OLE API function.
-
Win32::BuildNumber()
-
Returns the build number of Perl for Win32.
-
Win32::LoginName()
-
Returns the username of the owner of the current Perl process.
-
Win32::NodeName()
-
Returns the Microsoft network node-name of the current machine.
-
Win32::DomainName()
-
Returns the name of the Microsoft network domain that the owner of the current Perl process is logged into.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! -
- OLE Automation
- Content preview·Buy reprint rights for this chapterThe Win32::OLE modules give Perl support for OLE automation. OLE automation is a Microsoft technology based on COM that allows objects created by another application to be used and manipulated by a program through a common interface.The application (or DLL) that implements the automation interface is called the automation server. The application that creates and uses the interface is called the automation controller or automation client. Many popular applications expose their objects through automation. Microsoft Word, Excel, and other Office applications can be used as automation servers. Automation is widely used by Active Server Pages (ASP) and CGI scripts to access data repositories, perhaps via ActiveX Data Objects (ADO). You can even use automation to control many development environments and editors.In order to create an automation object, the server needs to be registered on the system. This is typically done by the server's installation program, but can be done manually using a utility like regsvr32.exe. This involves adding entries to the system registry to tell COM how to find the component, what types of interfaces it provides, what type of server it is, etc. You should be able to find the object model, available methods and properties of the interface in the documentation provided by the application. This object model can be used via Perl's object syntax to create and control objects in your programs.Four modules provide automation functionality to Perl:
- Win32::OLE
-
Provides the main interface for OLE automation. You can create or open automation objects, use their methods, and set their properties.
- Win32::OLE::Enum
-
Creates objects for collections and defines an interface for enumerating them.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Chapter 20: PerlScript
- Content preview·Buy reprint rights for this chapterPerlScript is an ActiveX scripting engine that allows you to incorporate Perl within any ActiveX scripting host. PerlScript can be used on the client side (Internet Explorer 4.0) or in Active Server Pages (ASP) generated by web servers like IIS or WebSite Pro. To use PerlScript with these applications, you must have Active State's ActivePerl with PerlScript installed on the local machine (or you can use a network-based installation of each).Since a local Perl and PerlScript installation is required, it is not practical to deploy applications that use client-side PerlScript across the Internet. Nevertheless, in situations where you have control over the desktop configurations, as in an Intranet environment, client-side PerlScript offers tremendous opportunities for browser-based application development.Server-side PerlScript does not have this limitation. To use PerlScript on your web server, you don't need to worry about how the end user's desktop is configured. As long as you are running a web server that can use ASP, you can use PerlScript on your web server.With the free distribution of Netscape Navigator source code, the availability of PerlScript is likely to broaden significantly. This is an area of development that you should keep an eye on if you like the idea of extending Perl's power to web authoring.PerlScript is implemented into HTML pages or ASP pages via the Document Object Model used by the ActiveX scripting engine. Scripts are virtually the same as any other Perl script. They use Perl's object-oriented features on an object hierarchy defined by the script engine. The object model is different for clients and servers, but the same scheme is used throughout: top-level objects with sub-objects, each containing their own properties and methods.Properties of objects, like the name of a frame or the background color of a window, are available as hash elements from a referenced object. For example:
$object->subobject{'property'} = "value"; $val = $object->subobject->{'property'};
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Client-Side PerlScript
- Content preview·Buy reprint rights for this chapterAll PerlScript code must be contained within a
<SCRIPT LANGUAGE="PerlScript"></SCRIPT>
element. You may include any number of these elements in your program, so it is possible to intersperse Perl and HTML freely. For example:<HTML> <HEAD> <TITLE>Hello, World</TITLE> </HEAD> <BODY> <H1>Hello, from the Old Edition!</H1> <SCRIPT LANGUAGE="PerlScript"> my @one_hit = ('Bel', 'Biv', 'DeVoe'); foreach (@one_hit) { $window->document->write(qq[$_ says "Hello"!<BR>]); } $window->document->write(qq[<P><I>"That girl is Poison!"</I></P>]); </SCRIPT> </BODY> </HTML>
Thewrite
method is used on the document object to "write" HTML and text to the document displayed in the window.The top-level object is the window. This is the default object that contains the script. (Even though the script is contained in the HTML file, the script object is a level below the window, just like the document object.)Every window contains the following objects:- Frame
-
This object contains an array of frames in the window. Each frame object is accessible via the index, i.e.,
$window->frame[2]
is the third frame object. Each frame object is a container that acts like its own window object. - History
-
This object stores the browser history—all the sites a client has been to in its current session.
- Navigator
-
This object contains information about the client application, like the UserAgent header it provides.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing! - Server-Side PerlScript
- Content preview·Buy reprint rights for this chapterPerlScript on the server-side of business is a much more viable method of incorporating Perl into your web applications. You can use PerlScript as the scripting language for Active Server Pages (ASP), which are used by such applications as Microsoft's IIS and O'Reilly's WebSite Pro. See the documentation for these products to properly set up ASP on your server. ActivePerl with PerlScript must be installed on the server machine to be used with ASP.Active Server Pages use PerlScript in pages much like client-side scripting except that the object model is different, and most importantly, the script is executed on the server. When an Active Server Page is requested, the .asp file is processed, scripts are executed, and an HTML page is produced and delivered to the client.Each script is contained within
<SCRIPT>
tags. PerlScript must be declared as the default scripting language for each file with:<SCRIPT LANGUAGE="PerlScript" RUNAT=Server>
TheRUNAT
attribute signals that the script is to be executed on the server and not the client. The lines of the script follow, and the script is closed with an ending</SCRIPT>
tag.An alternative syntax to the<SCRIPT>
tags are the<% %>
delimiters. These are not HTML tags, but indicate that whatever happens between them is to be executed. There are also special constructs used with these delimiters. Since they can be interspersed with HTML throughout a file, the default language must be declared at the top of the file with the<%@ %>
tag:<%@ PerlScript%>
This delimiter syntax completely replaces the declarative<SCRIPT>
tag shown above, but it must be placed at the top of any file using the<% %>
syntax for scripting. In addition to this tag, you can use the<%= %>
tag throughout your file to automatically assign a value to the output of your file (i.e., a$Response->write
function). Here is an example:<%@ PerlScript> <HTML> <HEAD></HEAD> <BODY> <H1>Say Hello, Boys!</H1> <% my @onehit = ("Bel", "Biv", "DeVoe"); %> <P> <%= $onehit[0] %> says "Hello." <BR> <%= $onehit[1] %> says "Hello." <BR> <%= $onehit[2] %> says "Hello." </P> </BODY> </HTML>
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Return to Perl in a Nutshell
About O'Reilly | Contact | Jobs | Press Room | How to Advertise | Privacy Policy
© 2008, O'Reilly Media, Inc.
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.