Perl 5
by Example
by David Medinets
C O N T E N T S
Chapter 1
Getting Your Feet Wet
Chapter 2
Numeric and String Literals
Chapter 3
Variables
Chapter 4
Operators
Chapter 5
FuNCtions
Chapter 6
Statements
Chapter 7
Control Statements
Chapter 8
RefereNCes
Chapter 9
Using Files
Chapter 10
Regular Expressions
Chapter 11
Creating Reports
Chapter 12
Using Special Variables
Chapter 13
Handling Errors and Signals
Chapter 14
What Are Objects?
Chapter 15
Perl Modules
Chapter 16
Debugging Perl
Chapter 17
Using Command-Line Options
Chapter 18
Using Internet Protocols
Chapter 19
What Is CGI?
Chapter 20
Form Processing
Chapter 21
Using Perl with Web Servers
Chapter 22
Internet Resources
Appendix B
Glossary
Appendix C
FuNCtion List
-
FuNCtions by Category
-
FuNCtions by Name
-
abs([EXPR])
-
accept (NEWSOCKET, GENERICSOCKET)
-
alarm (NUM_OF_SECONDS)
-
atan2 ([EXPR])
-
bind (SOCKET, NAME)
-
binmode (FILEHANDLE)
-
bless (REFERENCE, [CLASSNAME])
-
caller ([EXPR])
-
chdir ([DIRNAME])
-
chmod (MODE, LIST)
-
chomp ([STRING | LIST])
-
chop ([STRING | LIST])
-
chown (NUMERICAL_UID, NUMERICAL_GID, LIST)
-
chr (NUMBER)
-
chroot (DIR_NAME)
-
close (FILEHANDLE)
-
closedir (DIRHANDLE)
-
connect (SOCKET, NAME)
-
cos ([EXPR])
-
crypt (TEXT, SALT)
-
dbmclose (HASH)
-
dbmopen (HASH, DATABASE_NAME, MODE)
-
defined (EXPR)
-
delete (EXPR)
-
die ([LIST])
-
do (SCRIPTNAME)
-
dump ([LABEL])
-
each (HASH)
-
endgrent ( )
-
endhostent ( )
-
endnetent ( )
-
endprotoent ( )
-
endpwent ( )
-
endservent ( )
-
eof ([FILEHANDLE])
-
eval ([EXPR | BLOCK])
-
exec (LIST)
-
exists (EXPR)
-
exit ([EXPR])
-
exp ([EXPR])
-
fcntl (FILEHANDLE, FUNCTION, PACKED_FLAGS)
-
fileno (FILEHANDLE)
-
flock (FILEHANDLE, OPERATION_FLAGS)
-
fork ( )
-
formline (PICTURE, LIST)
-
getc ([FILEHANDLE])
-
getgrent ( )
-
getgrgid (GID)
-
getgrname (NAME)
-
gethostbyaddr (ADDRESS, AF_INIT)
-
gethostbyname (NAME, [PROTOCOL])
-
gethostent ( )
-
getlogin ( )
-
getnetbyaddr (ADDRESS, ADDR_TYPE)
-
getnetbyname (NAME)
-
getnetent ( )
-
getpeername (SOCKET)
-
getpgrp (PID)
-
getppid ( )
-
getpriority (WHICH, WHO)
-
getprotobyname (NAME)
-
getprotobynumber (NUMBER)
-
getprotoent ( )
-
getpwent ( )
-
getpwnam (NAME)
-
getpwuid (UID)
-
getservbyname (NAME, PROTOCOL)
-
getservbyport (PORT_NUMBER, PROTOCOL)
-
getservent ( )
-
getsockname (SOCKET)
-
getsockopt (SOCKET, LEVEL, OPTNAME)
-
glob (EXPR)
-
gmtime ([EXPR])
-
grep (BLOCK | EXPR, LIST)
-
hex (EXPR)
-
import ( )
-
index (STRING, SUBSTRING, [POSITION])
-
int ([EXPR])
-
ioctl (FILEHANDLE, FUNCTION, SCALAR)
-
join (EXPR, LIST)
-
keys (HASH)
-
kill (SIGNAL, LIST)
-
lc (EXPR)
-
lcfirst (EXPR)
-
length ([EXPR])
-
link (OLD_FILE, NEW_FILE)
-
listen (SOCKET, QUEUESIZE)
-
local (LIST)
-
localtime ([EXPR])
-
log ([EXPR])
-
lstat (FILEHANDLE | EXPR)
-
map (BLOCK | EXPR, LIST)
-
mkdir (FILENAME, [MODE])
-
msgctl (ID, COMMAND, ARG)
-
msgget (KEY, FLAGS)
-
msgrcv (QUEUE_ID, BUFFER, BUFFER_SIZE, TYPE, FLAGS)
-
msgsnd (QUEUE_ID, BUFFER, FLAGS)
-
my (LIST)
-
oct ([EXPR])
-
open (FILEHANDLE | EXPR | FILENAME)
-
opendir (DIRHANDLE, EXPR | DIRNAME)
-
ord ([EXPR])
-
pack (TEMPLATE, LIST)
-
pipe (READHANDLE, WRITEHANDLE)
-
pop (ARRAY_VARIABLE)
-
pos ([SCALAR])
-
print [FILEHANDLE] ([LIST])
-
printf [FILEHANDLE] (FORMAT, LIST)
-
push (ARRAY, LIST)
-
q (LIST)
-
qq (LIST)
-
quotemeta (EXPR)
-
qw (LIST)
-
qx (LIST)
-
rand ([EXPR])
-
read (FILEHANDLE, BUFFER, LENGTH, [OFFSET])
-
readdir (DIRHANDLE)
-
readlink ([EXPR])
-
recv (SOCKET, BUFFER, LENGTH, FLAGS)
-
ref (EXPR)
-
rename (OLDNAME, NEWNAME)
-
reset ([EXPR])
-
reverse (LIST)
-
rewinddir (DIRHANDLE)
-
rindex (STRING, SUBSTRING, [POSITION])
-
rmdir ([DIRNAME])
-
scalar (EXPR)
-
seek (FILEHANDLE, POSITION, WHENCE)
-
seekdir (DIRHANDLE, POS)
-
select ([FILEHANDLE])
-
select (RBITS, WBITS, EBITS, TIMEOUT)
-
semctl (ID, SEMNUM, CMD, ARG)
-
semget (KEY, NSEMS, FLAGS)
-
semop (KEY, OPSTRING)
-
send (SOCKET, BUFFER, FLAGS, [TO])
-
setgrent ( )
-
sethostent (STAYOPEN)
-
setnetent (STAYOPEN)
-
setpgrp (PID, PGRP)
-
setpriority (WHICH, WHO, PRIORITY)
-
setprotoent (STAYOPEN)
-
setpwent
-
setservent (STAYOPEN)
-
setsockopt (SOCKET, LEVEL, OPTNAME, OPTVAL)
-
shift ([ARRAY])
-
shmctl (ID, CMD, ARG)
-
shmget (KEY, SIZE, FLAGS)
-
shmread (ID, BUFFER, POS, SIZE)
-
shmwrite (ID, BUFFER, POS, SIZE)
-
shutdown (SOCKET, HOW)
-
sin ([EXPR])
-
sleep ([NUM_SECONDS_TO_SLEEP])
-
socket (SOCKET, DOMAIN, TYPE, PROTOCOL)
-
socketpair (SOCKET1, SOCKET2, DOMAIN, TYPE, PROTOCOL)
-
sort ([SUBNAME | BLOCK], LIST)
-
splice (ARRAY, OFFSET, [LENGTH], [LIST])
-
split ([/PATTERN/], [EXPR], [LIMIT])
-
sprintf (FORMAT, LIST)
-
sqrt ([EXPR])
-
srand ([EXPR])
-
stat (FILEHANDLE | EXPR)
-
study ([SCALAR])
-
substr (EXPR, OFFSET, [LEN])
-
symlink (OLDFILE, NEWFILE)
-
syscall (LIST)
-
sysopen (FILEHANDLE, FILENAME, MODE, [PERMISSIONS])
-
sysread (FILEHANDLE, BUFFER, LENGTH, [OFFSET])
-
system (LIST)
-
syswrite (FILEHANDLE, BUFFER, LENGTH, [OFFSET])
-
tell ([FILEHANDLE])
-
telldir (DIRHANDLE)
-
tie (VARIABLE, PACKAGENAME, LIST)
-
tied (VARIABLE)
-
time ( )
-
times ( )
-
truNCate (FILEHANDLE | EXPR, LENGTH)
-
uc (EXPR)
-
ucfirst (EXPR)
-
umask ([EXPR])
-
undef ([EXPR])
-
unlink (LIST)
-
unpack (TEMPLATE, EXPR)
-
unshift (ARRAY, LIST)
-
untie (VARIABLE)
-
utime (AccESS_TIME, MODIFICATION_TIME, LIST)
-
values (HASH)
-
vec (EXPR, OFFSET, NUM_BITS)
-
wait ( )
-
waitpid (PID, FLAGS)
-
wantarray ( )
-
warn ([LIST])
-
write ([FILEHANDLE | EXPR])
Appendix D
Using the Registry
Copyright© 1996 by Que Corporation.
All rights reserved. Printed in the United States of America.
No part of this book may be used or reproduced in any form or
by any means, or stored in a database or retrieval system, without
prior written permission of the publisher except in the case of
brief quotations embodied in critical articles and reviews. Making
copies of any part of this book for any purpose other than your
own personal use is a violation of United States copyright laws.
For information, address Que Corporation, 201 W. 103rd Street,
Indianapolis, IN 46290. You may reach Que's direct sales line
by calling 1-800-428-5331.
ISBN: 0-7897-0866-3
HTML conversion by :
M/s. LeafWriters (India) Pvt. Ltd.
Website : http://leaf.stpn.soft.net
e-mail :
leafwriters@leaf.stpn.soft.net
President | Roland Elgey
|
Publisher | Joseph B. Wikert
|
Director of Marketing
| Lynn E. Zingraf
|
Editorial Services Director
| Elizabeth Keaffaber
| Managing Editor
| Sandy Doell |
Title Manager |
Bryan Gambrel | Project Director
| Al Valvano |
Production Editors
| Susan Ross Moore, Matthew B. Cox
| Editors | Elizabeth Barrett, Anne Owen, Jeff Riley
|
Product Marketing Manager
| Kim Margolius |
Assistant Product Marketing Manager
| Christy M. Miller
|
Technical Editors
| Joe Milton, J. David Shinn, CNE, Synergetic Resource Corp.
| Technical Specialist
| Nadeem Muhammed
|
Acquisitions Coordinator
| Carmen Krikorian
| Operations Coordinator
| Patricia J. Brooks
|
Editorial Assistant
| Andrea Duvall |
Book Designer | Barb Kordesh
|
Cover Designer |
Ruth Harvey | Production
| Bryan Flores |
About the Author
David Medinets has been programming since 1980, when he
started with a TRS-80 Model 1. He still fondly remembers the days
when he could crosswire the keyboard to create funny-looking characters
on the display. SiNCe those days, he has spent time debugging
Emacs on UNIX machines, working on VAXen, and messing around with
DOS microcomputers. David is married to Kathryn and lives in northwest
New Jersey. He runs Eclectic Consulting and has coauthored
Special Edition Using Lotus Notes Release 4 (Que), Special
Edition Using Turbo C++ 4.5 for Windows (Que), Microsoft
Office 95 Unleashed (Sams), and Visual Basic Unleashed
(Sams), among others. David can be reached at medined@planet.net.
Acknowledgments
I'd like to thank all of the people at Que for making this book
possible. You'll find their names listed on the Credits page,
so I won't list them all here. Susan Ross Moore deserves special
thanks for figuratively watching over my shoulder as I worked.
Her comments definitely made this a better book. Al Valvano was
instrumental in making sure that everything came together at the
proper time.
My wonderful wife deserves some thanks for letting me hang out
on the Internet at all hours of the day and night while I did
research for this book.
While writing this book, I have gleaned information from many
books, articles, and Web resources. Where a particular item greatly
influeNCed my thinking, I have given credit in the appropriate
section.
Dale Bewley helped to create Chapter 19, "What Is CGI?"-Thanks
Dale!
And of course, no Perl author should forget to thank: Larry Wall
for creating Perl in the first place; Tom Christiansen for his
remarkable contributions to the Perl community; and Randal Schwartz
for his Learning Perl book which every Perl programmer seems to
have read.
Thanks,
David
We'd Like to Hear from You!
As part of our continuing effort to produce books of the highest
possible quality, Que would like to hear your comments. To stay
competitive, we really want you, as a computer book reader
and user, to let us know what you like or dislike most about this
book or other Que products.
You can mail comments, ideas, or suggestions for improving future
editions to the address below, or send us a fax at (317) 581-4663.
Our staff and authors are available for questions and comments
through our Internet site, at http://www.mcp.com/que, and Macmillan
Computer Publishing also has a forum on CompuServe (type GO
QUEBOOKS at any prompt).
In addition to exploring our forum, please feel free to contact
me personally to discuss your opinions of this book: I'm avalvano@que.mcp.com
on the Internet, and 74671,3710 on CompuServe.
Thanks in advaNCe-your comments will help us to continue publishing
the best books available on new computer technologies in today's
market.
Al Valvano
Project Director
Que Corporation
201 W. 103rd Street
Indianapolis, Indiana 46290
USA
Introduction
This book is based on the learn-by-doing priNCiple because I believe
that simply reading about a subject makes it harder to learn.
After all, you don't read about putting together a jigsaw puzzle;
you put the puzzle together yourself! Programming is the same
way. You must actually run some programs in order to really understand
the coNCepts.
Perl 5 By Example will teach you how to use the Perl programming
language by showing examples that demonstrate the coNCepts being
discussed. The examples are designed to give you a chaNCe to experiment-which
in turn should clarify the material.
Additional information and errata pages can be found at http://www.mtolive.
com/pbe/index.html.
The topics are covered in a straightforward, nontechnical manner,
which allows you to quickly understand the fundamental priNCiples.
After the main topic of each chapter is introduced, subtopics
are explored in their own sections. Each section has its own Perl
examples with explanations given in pseudocode.
Each chapter finishes with review questions of varying difficulty
based on the material in that chapter. The answers usually come
from the text or are deducible from the text, but occasionally
you might need to experiment a little. Try to answer the questions
at all difficulty levels. If you get stuck turn to the answers
provided in Appendix A. Also, look at the summary sections after
reading each chapter and return to them frequently. After you've
gone through several chapters, you'll begin to understand more
often the reason why a coNCept was illustrated or a question was
asked. Returning to questions that frustrated you earlier and
realizing that now you know the answers can be a big confideNCe
builder.
Who Should Use This Book?
Perl 5 By Example should be read by anyone seeking to learn
Perl. If you don't know any other programming languages, Chapters
2 through 7 will give you a solid introduction to the basics.
If you already know another language, then skip Chapters 2 through
7 to see how Perl differs from other languages and start with
Chapter 8, "RefereNCes."
This book follows a simple format. Each chapter contains a single
topic-usually. First, you read about the topic and then you see
examples that let you work directly with Perl to understand how
the coNCepts can be applied to a program. At the end of each chapter
is a summary, followed by review questions and exercises.
This approach is designed to serve a broad range of readers from
novice to advaNCed. If you've never programmed before, the learn-by-doing
approach will help you move quickly and easily though this book.
If you have programming experieNCe, you'll find plenty of material
to refine and enhaNCe what you already know, and to give you a
solid understanding of how Perl works.
What Do I Need?
In order to effectively use this book you need two things. You
need a working copy of Perl 5. And you need a text editor. That's
it.
You can use the examples in this book with just about any hardware
and operating system. I'm not sure that they would work on an
Amiga system but other than that you should be able to run every
example.
How to Use This Book
There are several ways to use this book. One obvious method is
to begin at the first page and proceed in order until the last.
Most beginning programmers will use this method and the book is
specifically designed so that each chapter builds on the last.
Alternatively, you can read up to Chapter 10, "Regular Expressions,"
and then skip to Appendix C, "FuNCtion List." You can
then read specific chapters as needed when your projects demand
them. Either approach works.
Tip |
It is critical to read through the FuNCtion List
(Appendix C) at least oNCe before starting any major project.
Otherwise, you might spend hours developing a fuNCtion that Perl
already has predefined.
|
Code Listings
Many readers prefer to type in most of the example code by hand;
this helps them focus on the code one line at a time. Another
good approach is to work through an example in a chapter, close
the book, and enter it by hand from memory. The struggle that
you experieNCe will help to deepen your understanding. Remember,
getting lost can be how you learn to find your way.
If you're lazy, can't type fast, or are prone to wrist pains like
some of my friends, you can copy the listings from the CD-ROM
that is iNCluded at the back of this book. Each listing that is
on the CD-ROM has a listing header like this:
Listing 10.1 10LST01.PL-This Is a Sample Listing
Header
The name of the Perl source file will always be the same as the
listing's number.
After each example, experiment a little and see what happens.
Change a few things, or add a couple, and change the code a bit.
This will help you enjoy the learning experieNCe more. The most
important attribute of a successful learning experieNCe is fun.
If it is fun and you enjoy it, you will stay with it longer.
Conventions
The following conventions are used in this book:
- Code line, fuNCtions, variable names, and any text you see
on-screen appear in a special monospace
typeface.
- File names are also set in a monospace
typeface.
- New terms are in italic.
- Case is very important in Perl programming. Always pay attention
to uppercase and lowercase in variable and fuNCtion names.
- If you are required to type text, the text you must type will
appear in boldface. For example, "Type perl -w test.pl."
Usually, however, the line is set off by itself in a monospace
typeface, as shown in the following example: perl -w test.pl
Icons Used in This Book
Pseudocode is a special way of explaining a section of code with
an understandable, English language description. You often see
pseudocode before a code example. The following icon represents
pseudocode:
Overview
Part I, "Basic Perl," consists of the first eight chapters
of this book. These chapters discuss the fundamentals of Perl.
Chapter 1, "Getting Your Feet Wet," presents a short
history of Perl and lets you create and execute your first Perl
program. Chapter 2, "Numeric and String Literals," tells
you how to explicitly represent non-changeable information in
your program. Chapter 3, "Variables," shows how to represent
changeable information. Then Chapter 4, "Operators,"
discusses how to change the information. Chapter 5, "FuNCtions,"
discusses how to create parcels of code that you can call or execute
by name. Chapter 6, "Statements," dives deep into exactly
what the term statement means to Perl. Chapter 7, "Control
Statements," shows how different statements can be used to
control your programs. Chapter 8, "RefereNCes," completes
the introduction to Perl basics by taking a peek into the world
of data structures.
The next three chapters make up Part II, "Intermediate Perl."
These chapters contain valuable information that will let you
create powerful, complete applications. Chapter 9, "Using
Files," discusses how files can be used to store and retrieve
information. Chapter 10, "Regular Expressions," highlights
one of Perl's most useful abilities-pattern matching. Chapter
11, "Creating Reports," shows you how to present information
in a structured way using Perl's inherent reporting ability.
Part III, "AdvaNCed Perl," discusses some of the more
difficult aspects of Perl. Chapter 12, "Using Special Variables,"
lists all of the special variables that you use in Perl and shows
examples of the more useful ones. Chapter 13, "Handling Errors
and Signals," introduces the coNCept of error handling. Chapter
14, "What Are Objects?," discusses the wonderful world
of object-oriented programming. Chapter 15, "Perl Modules,"
shows you how to create your own modules to aid in reusing existing
fuNCtions. Chapter 16, "Debugging Perl," helps you to
find the bugs or problems in your programs. Chapter 17, "Using
the Command-Line Options," lists all of the options that
you can use on the command line that starts Perl.
Part IV, "Perl and the Internet," consists of five chapters
that look at how Perl can be used with the Internet. Chapter 18,
"Using Internet Protocols," discusses several of the
protocols commonly used on the Internet-such as FTP, SMTP, and
POP. Chapter 19, "What Is CGI?," eases you into writing
scripts that can be executed by remote users. Chapter 20, "Form
Processing," discusses HTML forms and how Perl scripts can
process form information. Chapter 21, "Using Perl with Web
Servers," examines Web server log file and how to create
HTML Web pages using Perl. Chapter 22, "Internet Resources,"
lists several types of Perl resources that are available on the
Internet-such as Usenet Newsgroups, Web sites, and the #perl
and #cgi IRC channels.
Appendix A, "Answers to Review Questions," contains
answers to the review questions that are at the end of every chapter.
Try not to peek! Appendix B, "Glossary," lists definitions
for some words you might be unfamiliar with. Appendix C, "FuNCtion
List," contains a list of Perl's many fuNCtions. Appendix
D, "Using the Registry," introduces you to the Registry
database used by Windows 95 and Windows NT to store system and
application information. Appendix E, "ASCII Table,"
shows you all of the ASCII codes and their corresponding characters.
Appendix F, "What's on the CD?," describes the contents
of the CD.