Tải bản đầy đủ (.pdf) (503 trang)

minimal perl for unix and linux people (2005)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.71 MB, 503 trang )

Minimal Perl

Minimal Perl
For UNIX and Linux People
BY TIM MAHER
MANNING
Greenwich
(74° w. long.)
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact:
Special Sales Department
Manning Publications Co.
Cherokee Station
PO Box 20386 Fax: (609) 877-8256
New York, NY 10021 email:
©2007 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Manning Publications Co. Copyeditor: Tiffany Taylor
209 Bruce Park Avenue Typesetters: Denis Dalinnik, Dottie Marsico
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 1-932394-50-8


Printed in the United States of America
12345678910–VHG–1009080706
To Yeshe Dolma Sherpa,
whose fortitude, endurance,
and many sacrifices made this book possible.
To my parents,
Gloria Grady Washington and William N. Maher,
who indulged my early interests in literature.
To my limbic system,
with gratitude for all the good times we’ve had together.

vii
brief contents
Part 1 Minimal Perl: for UNIX and Linux Users 1
1 Introducing Minimal Perl 3
2 Perl essentials 16
3 Perl as a (better) grep command 53
4 Perl as a (better) sed command 89
5 Perl as a (better) awk command 121
6 Perl as a (better) find command 178
Part 2 Minimal Perl: for UNIX and
Linux Shell Programmers 203
7 Built-in functions 205
8 Scripting techniques 247
9 List variables 295
10 Looping facilities 330
11 Subroutines and variable scoping 362
12 Modules and the CPAN 388

ix

contents
foreword xvii
preface xix
acknowledgments xxii
about this book xxiii
about the cover illustration xxxiv
list of tables xxxv
Part 1 Minimal Perl: for UNIX and Linux Users 1
1 Introducing Minimal Perl 3
1.1 A visit to Perlistan 3
Sometimes you need a professional guide 5
1.2 Perl can be simple 7
1.3 About Minimal Perl 7
What Minimal Perl isn’t 8 ✦ What Minimal Perl is 8
1.4 Laziness is a virtue 9
1.5 A minimal dose of syntax 10
Terminating statements with semicolons 10
1.6 Writing one-line programs 11
Balancing simplicity and readability 12
Implementing simple filters 12
1.7 Summary 14
2 Perl essentials 16
2.1 Perl’s invocation options 17
One-line programming: -e 18 ✦ Enabling warnings: -w 18
Processing input:
-n 19 ✦ Processing input with automatic
printing:
-p 19 ✦ Processing line-endings: -l 20 ✦ Printing
without newlines:
printf 21 ✦ Changing the input record

separator:
-0digits 22
x
2.2 Using variables 23
Using special variables 23 ✦ Using the data variable: $_ 24
Using the record-number variable:
$. 24 ✦ Employing
user-defined variables 25
2.3 Loading modules -M 27
2.4 Writing simple scripts 29
Quoting techniques 30 ✦ True and False values 32
Handling switches:
-s 32 ✦ Using warn and die 35
Using logical
and, logical or 37 ✦ Programming with BEGIN
and
END blocks 39 ✦ Loading modules with use 41
2.5 Additional special variables 42
Employing I/O variables 42 ✦ Exploiting formatting
variables 43
2.6 Standard option clusters 44
Using aliases for common types of Perl commands 46
2.7 Constructing programs 47
Constructing an output-only one-liner 49 ✦ Constructing
an input/output script 50
2.8 Summary 51
Directions for further study 51
3 Perl as a (better) grep command 53
3.1 A brief history of grep 53
3.2 Shortcomings of

grep 54
Uncertain support for metacharacters 54 ✦ Lack of string
escapes for control characters 56
✦ Comparing capabilities
of greppers and Perl 57
3.3 Working with the matching operator 60
The one-line Perl grepper 61
3.4 Understanding Perl’s regex notation 63
3.5 Perl as a better
fgrep 64
3.6 Displaying the match only, using
$& 64
3.7 Displaying unmatched records (like
grep -v)65
Validating data 66 ✦ Minimizing typing with shortcut
metacharacters 67
3.8 Displaying filenames only (like grep -l)67
3.9 Using matching modifiers 68
Ignoring case (like grep -i)70
xi
3.10 Perl as a better
egrep 70
Working with cascading filters 72
3.11 Matching in context 75
Paragraph mode 75 ✦ File mode 77
3.12 Spanning lines with regexes 77
Matching across lines 79 ✦ Using lwp-request 80
Filtering
lwp-request output 80
3.13 Additional examples 81

Log-file analysis 81 ✦ A scripted grepper 84
Fuzzy matching 85
✦ Web scraping 86
3.14 Summary 86
Directions for further study 88
4 Perl as a (better) sed command 89
4.1 A brief history of sed 89
4.2 Shortcomings of
sed 91
4.3 Performing substitutions 93
Performing line-specific substitutions: sed 96 ✦ Performing
line-specific substitutions: Perl 96
✦ Performing record-specific
substitutions: Perl 97
✦ Using backreferences and numbered
variables in substitutions 99
4.4 Printing lines by number 100
Printing lines by number: sed 100 ✦ Printing lines by number:
Perl 100
✦ Printing records by number: Perl 101
4.5 Modifying templates 101
4.6 Converting special characters 103
4.7 Editing files 105
Editing with commands 105 ✦ Editing with scripts 107
Safeguarding in-place editing 111
4.8 Converting to lowercase or uppercase 113
Quieting spam 113
4.9 Substitutions with computed replacements 114
Converting miles to kilometers 114 ✦ Substitutions using
function results 116

4.10 The sed to Perl translator 118
4.11 Summary 118
Directions for further study 120
xii
5 Perl as a (better) awk command 121
5.1 A brief history of AWK 122
5.2 Comparing basic features of
awk and Perl 123
Pattern-matching capabilities 124 ✦ Special variables 126
Perl’s variable interpolation 128
✦ Other advantages of
Perl over AWK 129
✦ Summary of differences in basic
features 129
5.3 Processing fields 130
Accessing fields 130 ✦ Printing fields 132 ✦ Differences
in syntax for
print 134 ✦ Using custom field separators
in Perl 136
5.4 Programming with Patterns and Actions 138
Combining pattern matching with field processing 142
Extracting data from tables 143
✦ Accessing cell data using
array indexing 145
5.5 Matching ranges of records 151
Operators for single- and multi-record ranges 152 ✦ Matching
a range of dates 153
✦ Matching multiple ranges 155
5.6 Using relational and arithmetic operators 157
Relational operators 157 ✦ Arithmetic operators 158

5.7 Using built-in functions 159
One-liners that use functions 161 ✦ The legend of nexpr 162
How the
nexpr* programs work 164
5.8 Additional examples 165
Computing compound interest: compound_interest 165
Conditionally pluralizing nouns:
compound_interest2 166
Analyzing log files:
scan4oops 168
5.9 Using the AWK-to-Perl translator: a2p 175
Tips on using a2p 175
5.10 Summary 175
Directions for further study 177
6 Perl as a (better) find command 178
6.1 Introducing hybrid find/perl programs 180
6.2 File testing capabilities of
find vs. Perl 180
Augmenting find with Perl 183
6.3 Finding files 184
Finding files by name matching 184 ✦ Finding files by
pathname matching 187
xiii
6.4 Processing filename arguments 188
Defending against grep’s messes 189 ✦ Recursive grepping 191
Perl as a generalized argument pre-processor 192
6.5 Using find | xargs vs. Perl alternatives 192
Using Perl for reliable timestamp sorting 193
Dealing with multi-word filenames 196
6.6 find as an argument pre-processor for Perl 197

6.7 A Unix-like, OS-portable
find command 198
Making the most of find2perl 198 ✦ Helping non-Unix
friends with
find2perl 199
6.8 Summary 200
Directions for further study 201
Part 2 Minimal Perl: for UNIX and
Linux Shell Programmers 203
7 Built-in functions 205
7.1 Understanding and managing evaluation context 206
Determinants and effects of evaluation context 207
Making use of evaluation context 208
7.2 Programming with functions that generate or
process scalars 210
Using split 211 ✦ Using localtime 214 ✦ Using
stat 215 ✦ Using chomp 219 ✦ Using rand 221
7.3 Programming with functions that process lists 223
Comparing Unix pipelines and Perl functions 223
Using
sort 224 ✦ Using grep 227 ✦ Using join 229
Using
map 232
7.4 Globbing for filenames 234
Tips on globbing 237
7.5 Managing files with functions 239
Handling multi-valued return codes 240
7.6 Parenthesizing function arguments 242
Controlling argument-gobbling functions 242
7.7 Summary 243

Directions for further study 245
xiv
8 Scripting techniques 247
8.1 Exploiting script-oriented functions 248
Defining defined 249 ✦ Exiting with exit 253
Shifting with
shift 254
8.2 Pre-processing arguments 256
Accommodating non-filename arguments with implicit loops 256
Filtering arguments 257
✦ Generating arguments 259
8.3 Executing code conditionally with if/else 259
Employing if/else vs. and/or 260 ✦ Mixing branching
techniques: The
cd_report script 261 ✦ Tips on using
if/else 264
8.4 Wrangling strings with concatenation and
repetition operators 265
Enhancing the most_recent_file script 267 ✦ Using
concatenation and repetition operators together 267
✦ Tips on
using the concatenation operator 268
8.5 Interpolating command output into source code 269
Using the tput command 271 ✦ Grepping recursively: The
rgrep script 273 ✦ Tips on using command interpolation 274
8.6 Executing OS commands using system 275
Generating reports 277 ✦ Tips on using system 280
8.7 Evaluating code using eval 283
Using a Perl shell: The psh script 284 ✦ Appreciating a
multi-faceted Perl grepper: The

preg script 286
8.8 Summary 292
Directions for further study 294
9 List variables 295
9.1 Using array variables 296
Initializing arrays with piecemeal assignments and push 299
Understanding advanced array indexing 300
✦ Extracting
fields in a friendlier fashion 301
✦ Telling fortunes:
The
fcookie script 304 ✦ Tips on using arrays 308
9.2 Using hash variables 308
Initializing hashes 311 ✦ Understanding advanced hash
indexing 312
✦ Understanding the built-in %ENV
hash 313
✦ Printing hashes 314 ✦ Using %ENV in
place of switches 315
✦ Obtaining uniqueness with
hashes 316
✦ Employing a hash as a simple database: The
user_lookup script 319 ✦ Counting word frequencies
in web pages: The
count_words script 323
xv
9.3 Comparing list generators in the Shell and Perl 325
Filename generation/globbing 326 ✦ Command substitution/
interpolation 327
✦ Variable substitution/interpolation 327

9.4 Summary 328
Directions for further study 329
10 Looping facilities 330
10.1 Looping facilities in the Shell and Perl 331
10.2 Looping with
while/until 333
Totaling numeric arguments 333 ✦ Reducing the size of an
image 335
✦ Printing key/value pairs from a hash using
each 336 ✦ Understanding the implicit loop 337
10.3 Looping with do while/until 338
Prompting for input 339
10.4 Looping with foreach 340
Unlinking files: the rm_files script 341 ✦ Reading a line at a
time 341
✦ Printing a hash 342 ✦ Demystifying acronyms:
The
expand_acronyms script 343 ✦ Reducing image sizes: The
compress_image2 script 344
10.5 Looping with for 345
Exploiting for’s support for indexing: the raffle script 347
10.6 Using loop-control directives 349
Nesting loops within loops 350 ✦ Enabling loop-control
directives in bottom-tested loops 351
✦ Prompting for
input 352
✦ Enhancing loops with continue blocks: the
confirmation script 353
10.7 The CPAN’s select loop for Perl 355
Avoiding the re-invention of the “choose-from-a-menu” wheel 356

Monitoring user activity: the
show_user script 357
Browsing man pages: the
perlman script 358
10.8 Summary 360
Directions for further study 361
11 Subroutines and variable scoping 362
11.1 Compartmentalizing code with subroutines 363
Defining and using subroutines 365 ✦ Understanding use
strict
368
11.2 Common problems with variables 370
Clobbering variables: The phone_home script 371 ✦ Masking
variables: The
4letter_word script 372 ✦ Tips on avoiding
problems with variables 373
xvi
11.3 Controlling variable scoping 373
Declaring variables with my 374 ✦ Declaring variables with
our 374 ✦ Declaring variables with local 375 ✦ Introducing
the Variable Scoping Guidelines 375
11.4 Variable Scoping Guidelines for complex programs 376
Enable use strict 377 ✦ Declare user-defined variables and
define their scopes 377
✦ Pass data to subroutines using
arguments 383
✦ Localize temporary changes to built-in variables
with
local 383 ✦ Employ user-defined loop variables 383
Applying the Guidelines: the

phone_home2 script 384
11.5 Reusing a subroutine 386
11.6 Summary 387
Directions for further study 387
12 Modules and the CPAN 388
12.1 Creating modules 389
Using the Simple Module Template 390 ✦ Creating a
module:
Center.pm 393 ✦ Testing a new module 395
12.2 Managing modules 398
Identifying the modules that you want 398 ✦ Determining
whether you have a certain module 400
✦ Installing
modules from the CPAN 401
12.3 Using modules 403
Business::UPS—the ups_shipping_price script 403
LWP::Simple—the check_links script 405
Shell::POSIX::Select—the menu_ls script 408
File::Find—the check_symlinks script 411
CGI—the survey.cgi script 414 ✦ Tips on using
Object-Oriented modules 422
12.4 Summary 424
Directions for further study 425
epilogue 426
appendix A: Perl special variables cheatsheet 427
appendix B: Guidelines for parenthesizing code 430
glossary 432
index 443
xvii
foreword

Perl is a lamb in wolf’s clothing. It has a ferocious reputation for incomprehensibility
(“executable line-noise”) and excessive power (“the Swiss-Army chainsaw”), but under-
neath lurks a kinder, gentler programming language than whatever you’re using now.
Of course, Perl can be complex. After all, very few other popular languages have
so many advanced built-in capabilities, which is one reason why Perl rates as one of
the most sophisticated programming languages in widespread use today.
Fortunately, unlike many other programming languages, Perl also comes standard
with one other vital feature: a gentle learning curve. You don’t have to understand a
multitude of high-end programming constructs before you can do useful work with
it. If you’re familiar with the basic tools of Unix/Linux—
grep, sed, awk, find, and
the shell itself—then many of the features of Perl will seem hauntingly familiar.
Perl’s creator, Larry Wall, once described his language as “a cleaned up and sum-
marized version of that wonderful semi-natural language known as ‘Unix.’” And that’s
precisely the direction from which this book leads you into the depths of the language:
by showing how Perl has evolved “Unix” into a dialect that is much more powerful
but also much easier to use. If you’re already fluent in Perl’s mother tongue, and you
want to discover how expressive and poetic Perl itself can be, you could have chosen
no better primer than this book and no better guide than Dr. Tim Maher, a gifted
teacher and a decorated veteran of both the Unix world and the Perl community.
So, welcome to Perl! You don’t have to come from *nix to work here…but it cer-
tainly helps.
D
AMIAN CONWAY

xix
preface
In this preface, I’ll tell you about the history of Minimal Perl and the origins of this
book.
THE HISTORY OF MINIMAL PERL

The seeds of this book were sown many years ago, when I was building up my knowl-
edge of Perl, the greatest programming language I’d ever encountered (before or since).
While reading a variety of books on the subject, I was surprised that the authors felt
obliged to delve into so many of the different but equivalent choices for expressing
every basic operation in the language, as well as each of the syntactic variations for
expressing any one of those choices.
As an example, I’ve shown here some of the available choices for expressing in Perl
the simple idea that
B should be executed only if A is True (with those letters repre-
senting arbitrary program elements). Both forward and backward variations for
expressing the dependency are included:
1
Although some are inclined to present symptoms like these of Perl’s complexity and
redundancy as evidence of its “richness,” “versatility,” or “expressiveness,” many Perl
novices would surely have a different reaction—that Perl is needlessly complex and too
hard to learn.
Minimal Perl was created to address these obstacles presented by Perl’s redundancy
and complexity. By emphasizing Perl’s
grep, sed, and awk-like features, and relying
Forward Backward
A and B; B if A;
A && B; B if A;
A and do { B }; do { B } if A;
A && do { B }; do { B } if A;
if (A) { B }; B if A;
unless (!A) { B }; B unless !A;
1
Before you despair, I should point out that Minimal Perl uses only 2 of these variations—which is all
anybody needs!
xx

on concepts such as inputs, filters, and arguments, it allows Unix
1
users to directly apply
their existing knowledge to the task of learning Perl. So rather than being frustrated
with Perl’s complexities and disappointed with its steep learning curve, they quickly
and painlessly acquire the ability to write useful programs that can solve a wide variety
of problems.
My first public presentation on this subject was in a tutorial called “Minimal Perl
for the Impatient” at the
YAPC::Europe 2001 conference
2
in Amsterdam, the Nether-
lands. The eagerness with which that audience devoured the material confirmed my
hunch that many were hungering for an easier way to learn Perl. Since then, I’ve
taught Minimal Perl at other professional conferences, at meetings of Perl Users
Groups in the
US and Canada, and to many Fortune 500 companies.
THE GENESIS OF THE BOOK
By 2001, the Minimal Perl approach had convincingly proven its ability to help Unix
people acquire Perl skills with relative ease. But many who could appreciate its benefits
never get to see conference presentations or attend corporate training classes, so I
became interested in making this information available to a wider audience.
However, I had some serious reservations about embarking on a book, having
heard many sobering stories from colleagues about the travails of authorship. Fortu-
nately, I received some encouragement that was instrumental in helping me decide to
go forward with this project, from a good friend—Dr. Damian Conway.
A little help from my friend
Damian and I first met after my presentation on the first “Perl Beautifier” at The Perl
Conference in 1998,
3

when he gently informed me that I could have categorized Perl
source code into its constituent elements by using a program he had written (in Perl’s
module format), rather than writing my own from scratch to attempt that difficult task.
After examining more of his ingenious modules and reading his excellent book
Object Oriented Perl,
4
I soon realized that Damian had a deeper understanding of Perl
than almost anyone else. To allow others to benefit from his insights, I arranged for
him to periodically teach Perl classes through my Seattle-based company (Consultix)
and also to present talks to our Seattle Perl Users Group (
SPUG, aka Seattle.pm). This
worked out wonderfully for Seattleites, who would learn practical Perl incantations
1
In this book, Unix is shorthand for “UNIX, Linux, and related operating systems,” as detailed in the
“Essential terminology” section of “About this book.”
2
See this book’s glossary for the definition of YAPC.
3
For more details, see />4
His book is described at It’s for a more advanced audience than
this one.
xxi
from him during the formal daytime sessions and then enjoy his overtly hilarious (yet
covertly educational) conference-style presentations by night.
Damian is probably still blushing from my effusive introductions of him as
• The Perl Wonder from Down Under (because he’s an Aussie), and
• The Supreme Modulator of Perl.
1
But I feel vindicated, because by now everybody knows I was correct in my estimation
of his uniqueness and importance to the Perl community.

An auspicious weather non-event
During one week while Damian was in Seattle as a visiting instructor for Consultix, we
took an extended bike ride along the shore of Lake Washington together—and we
didn’t even get drenched by rain! As a long-time Seattleite, I knew this to be an
extremely auspicious sign, so I seized the opportunity to tell him about my interest in
writing a Minimal Perl book. Being a fellow fan of the
AWK language (which is Perlish,
but simpler)—and having a keen interest in making Perl more accessible to novices—
he expressed enthusiasm for the project and offered some interesting ideas about how
to approach it.
The combination of my ideas with some of Damian’s—along with sufficient fer-
mentation and seasoning—ultimately led to the format, content, and approach of the
book you now hold. The result is a volume that teaches Perl in ways no book has done
before! I hope you enjoy reading it as much as I did writing it.
1
This is a reference to his unique ability to crank out amazingly ambitious and advanced Perl modules
that mortal hackers dread even to contemplate, let alone code at blazingly high speeds.
xxii
acknowledgments
When I founded the Seattle Perl Users Group (SPUG) early in 1998,
1
I half-jokingly
told the members that my motivation was to collect as many Perl experts together as
possible, so I could learn everything they knew. At the time, I had no idea how much
I would ultimately learn from them—or how convenient it would be to have ready
access to 400+ Perl fanatics when it came time to round up technical reviewers for this
book! On both counts, I’m glad to be indebted to so many of the members of
SPUG.
I’m happy to acknowledge the assistance of the following individuals for providing
insightful comments on early drafts of this book: Kurt deMaagd, Keith Tarbell, Ben

Reser, Brian Wisti, Brian Maher (no relation to me), Brian Downs, Randy Kobes, Erik
J. Pearson, Michael Wallendahl, Ken Meyer, Gareth Beale, Ashok Misra, Bellam
Prakasa, Brian Maddux, Creede Lambard, Chris Whip, Steven Herber, C. J. Collier,
Jarod Wilson, Phil Moeck, David Innes, Joel Grow, John Creech, Rob Blomquist,
Neil Fryer, Reuven M. Lerner, Paul Campbell, and Stuart Kendrick.
I’m even more deeply indebted to the following intrepid souls, whose generous
contributions of time, effort, and sage guidance went far beyond even my most opti-
mistic expectations: Damian Conway, Jon Allen, Christie Robertson, Peter Scott,
David Dyck, Joe Knape, Dan Sanderson, and Michael R. Wolf.
I’m also grateful to the helpful folks at Manning for their assistance during all
phases of this book’s development—especially the publisher, Marjan Bace, for his wis-
dom, patience, and many indulgences.
Like all
JAPHs, I’m grateful to Larry for giving us the gift of Perl, but also for gen-
erously answering my questions on Perl’s finer details—even while balancing his laptop
on one arm to consult Perl’s source code while dashing down the hotel escalator to his next
conference talk. What a guy!
Finally, all my remaining gratitude goes to my wife, Yeshe Dolma Sherpa, who
endured seemingly endless periods of husbandly inattention while I was writing
this book.
1
Although this group is now also known by its Perl Mongers (see ) moniker of Seat-
tle. pm, that organization didn’t yet exist at the time of our formation, so our initial name is still our
official one. For more on the history of SPUG, which has been recognized as one of the oldest, largest,
and best Perl User Groups, see />xxiii
about this book
It would have been easy to write a truly “minimal” book on Perl by revealing so little
of the language that nobody would have been able to do much with it. This isn’t that
kind of book.
It would also have been easy to write yet another “maximal” book on Perl, which

would spend so much ink enthusing over its expressiveness, reveling in its redundan-
cies, frolicking through its freakier features, and rampaging through its ribald regions,
that there’d be insufficient room left to adequately explain how realistic programs
actually work or to give you practical tips on avoiding common problems. This isn’t
that kind of book either.
This is a new kind of Perl book—one that empowers you to write lots of useful pro-
grams, without learning any more about Perl than is necessary.
Why, you may be excused for asking, is this book so big for one having “Minimal”
in its title? There are three reasons. First, it contains dozens of practical programs
showing what you can do with this subset of the language, accompanied by detailed
explanations of their workings. Second, it shows helpful comparisons between funda-
mental features of the Shell programming language and their Perl counterparts (in
part 2). Third, the essential technical details of all topics are presented in tabular form
to maximize the utility of this volume as a reference book.
As a testament to what you can do with Minimal Perl, this book features program-
ming examples drawn from a wide variety of application areas, including system
administration, networking, web development, web scraping,
HTML processing, CGI
programming, databases, log-file analysis, financial calculations, file management, pat-
tern matching, field processing, data validation, report generation, file conversion, and
text parsing—among others.
We’ll discuss the target audience for this book next.
AUDIENCE AND ORGANIZATION
This book has two parts, aimed at those with different types of prior experience in
a Unix environment. The first part is for those with at least a Unix user’s
background, and the second part is for those who additionally have a Shell pro-
grammer’s background.
1
1
As explained under “Essential terminology,” Shell refers to a group of related Unix shells.

xxiv
Part 1: Perl for UNIX and Linux users
Part 1 gives those with at least user-level Unix skills—which includes even the most
advanced programmers—a gentle introduction to the core elements of Minimal Perl.
After reading it, you’ll be able to write custom programs to do the most common types
of data-processing tasks.
You’re assumed to be familiar with the most basic commands, file-management
techniques, and command formats used on Unix systems. For example, you should
know how to view the contents of text files, how to change the current directory with-
out getting lost, and how to use the
grep command to extract matching lines from
a file.
Readers with more extensive backgrounds in Shell programming can especially
benefit from part 2.
Part 2: Perl for UNIX and Linux Shell programmers
Part 2 helps Shell programmers capitalize on their specialized knowledge to quickly
acquire Perl skills that go beyond those learned in part 1. A basic understanding of
Shell variables,
I/O techniques, flow-control facilities, and other fundamental features
of the Bourne, Korn, Bash, or
POSIX shells is assumed.
If you lack this more advanced knowledge, you may still benefit from this material
after assimilating the lessons of part 1. But you should focus on the Perl syntax descrip-
tions, rather than the Shell-to-Perl translation aids (which aren’t designed for your
use). The same advice holds for programmers who specialize in the C shell, which is
fundamentally different from the Shells emphasized in this book.
We’ll discuss the book’s other resources next.
Reference materials
Some handy reference materials are provided in the back of the book, including the
“Perl special variables cheatsheet” (appendix A) and “Guidelines for parenthesizing

code” (appendix B). A glossary is also provided, to explain special terms such as direc-
tive,
JAPHly, and clobberation.
Some comments on the approach used in writing this book come next.
AUTHOR’S APPROACH
Before diving into this book, it may help you to understand my approach in writing it
and the pedagogical tricks and techniques I’ve used to maximize your benefits from
reading it.
First, we’ll talk about the features that increase this book’s value as a reference
work.
Reference value
After your initial reading, you’ll want to use this volume as a reference work. To help
you bypass the text and rapidly locate the essential technical details, I’ve packaged

×