sams teach yourself perl in 21 days teach...vi sams teach yourself perl in 21 days 00 0355 fm 5/9/02...

699

Upload: others

Post on 03-Feb-2021

8 views

Category:

Documents


0 download

TRANSCRIPT

  • 800 East 96th St., Indianapolis, Indiana, 46240 USA

    Laura Lemaywith revisions by Rafe Colburn

    Perlin 21 Days

    Teach Yourself

    SECOND EDITION

    00 0355 fm 5/9/02 2:32 PM Page i

  • Sams Teach Yourself Perl in 21 Days,Second EditionCopyright © 2002 by Sams PublishingAll rights reserved. No part of this book shall be reproduced, stored in aretrieval system, or transmitted by any means, electronic, mechanical, photo-copying, recording, or otherwise, without written permission from the publish-er. No patent liability is assumed with respect to the use of the informationcontained herein. Although every precaution has been taken in the preparationof this book, the publisher and author assume no responsibility for errors oromissions. Neither is any liability assumed for damages resulting from the useof the information contained herein.

    International Standard Book Number: 0-672-32035-5

    Library of Congress Catalog Card Number: 00-105848

    Printed in the United States of America

    First Printing: June 2002

    05 04 03 02 4 3 2 1

    TrademarksAll terms mentioned in this book that are known to be trademarks or servicemarks have been appropriately capitalized. Sams cannot attest to the accuracyof this information. Use of a term in this book should not be regarded asaffecting the validity of any trademark or service mark.

    Warning and DisclaimerEvery effort has been made to make this book as complete and as accurate aspossible, but no warranty or fitness is implied. The information provided is onan “as is” basis. The authors and the publisher shall have neither liability orresponsibility to any person or entity with respect to any loss or damages aris-ing from the information contained in this book.

    ACQUISITIONS EDITORSMark TaberKatie Purdum

    DEVELOPMENT EDITORScott D. Meyers

    MANAGING EDITORCharlotte Clapp

    PROJECT EDITORAnthony Lawrence WesleyReitz III

    PRODUCTION EDITORChip Gardner

    INDEXERErika Millen

    TECHNICAL EDITORJason Pellerin

    INTERIOR DESIGNGary Adair

    COVER DESIGNAren Howell

    LAYOUT TECHNICIANSRebecca HarmonSusan GeiselmanStacey Richwine-DeRome

    00 0355 fm 5/9/02 2:32 PM Page ii

  • Contents at a GlanceIntroduction 1

    WEEK 1 Getting Started 5

    Day 1 An Introduction to Perl 7

    2 Working with Strings and Numbers (Scalar Data) 29

    3 More Scalar Data and Operators 57

    4 Working with Lists and Arrays 85

    5 Working with Hashes 115

    6 Conditionals and Loops 143

    7 Exploring a Few Longer Examples 175

    WEEK 2 Doing More 189

    Day 8 Manipulating Lists and Strings 191

    9 Pattern Matching with Regular Expressions 215

    10 Doing More with Regular Expressions 243

    11 Creating and Using Subroutines 269

    12 Debugging Perl 299

    13 Scope, Modules, and Importing Code 319

    14 Exploring a Few Longer Examples 353

    WEEK 3 Advanced Perl 379

    Day 15 Working with Files and I/O 381

    16 Using Perl for CGI Scripting 409

    17 Managing Files and Directories 437

    18 Perl and the Operating System 453

    19 Working with References 481

    20 Odds and Ends 523

    21 Exploring a Few Longer Examples 559

    00 0355 fm 5/9/02 2:32 PM Page iii

  • Appendixes 589

    A Perl Functions 591

    B Installing Perl on a Unix System 629

    C Installing Perl for Windows 639

    Index 645

    00 0355 fm 5/9/02 2:32 PM Page iv

  • ContentsIntroduction 1

    WEEK 1 Getting Started 5

    DAY 1 An Introduction to Perl 7

    What Is Perl and Where Did It Come From?..........................................................8Why Learn Perl? ......................................................................................................9Getting Started Programming in Perl ....................................................................12

    Installing Perl....................................................................................................12Perl One-Liners and Perl Scripts......................................................................13

    An Example: The Ubiquitous Hello World ..........................................................13Creating the One-Liner ....................................................................................14What to Do if It Doesn’t Work ........................................................................14How It Works....................................................................................................14

    Another Example: Create Hello World As a Script ..............................................15Create Hello World as a Script ........................................................................15Running the Hello World Script ......................................................................16What to Do if the Hello World Script Doesn’t Work ......................................17How Does It Work? ..........................................................................................17A Note About Warnings ..................................................................................18

    Another Example: Echo ........................................................................................19A Third Example: The Cookie Monster ................................................................20Going Deeper ........................................................................................................21

    Getting Perl Documentation ............................................................................22Getting Help ....................................................................................................22

    Summary ................................................................................................................23Q&A ......................................................................................................................23Workshop ..............................................................................................................25

    Quiz ..................................................................................................................25Exercises ..........................................................................................................26

    Answers..................................................................................................................26Quiz Answers....................................................................................................26Exercise Answers..............................................................................................28

    DAY 2 Working with Strings and Numbers (Scalar Data) 29

    Scalar Data and Scalar Variables ..........................................................................30Numbers............................................................................................................30Strings ..............................................................................................................31Converting Between Numbers and Strings ......................................................33Scalar Variables ................................................................................................33

    00 0355 fm 5/9/02 2:32 PM Page v

  • Constructing Perl Scripts ......................................................................................35Arithmetic Operators ............................................................................................36

    Arithmetic and Decimal Precision ..................................................................37One-Liners: Simple Calculator ..............................................................................38An Example: Converting Fahrenheit to Celsius ....................................................39Operators for Tests and Comparisons....................................................................40

    The Meaning of Truth ......................................................................................41Equality and Relational Operators ..................................................................41Logical Operators ............................................................................................43Pattern Matching ..............................................................................................45

    Another Example: More Cookies ..........................................................................46Going Deeper ........................................................................................................48

    Quoting Strings and Patterns............................................................................48Unquoted Strings (Barewords) ........................................................................49Upper and Lowercase Escapes ........................................................................49More About Variable Interpolation in Strings ..................................................50Octal and Hexadecimal Numbers ....................................................................50

    Summary ................................................................................................................50Q&A ......................................................................................................................51Workshop ..............................................................................................................52

    Quiz ..................................................................................................................52Exercises ..........................................................................................................53

    Answers..................................................................................................................53Quiz Answers....................................................................................................53Exercise Answers..............................................................................................54

    DAY 3 More Scalar Data and Operators 57

    Assignment Operators............................................................................................58Increment and Decrement Operators ....................................................................59String Concatenation and Repetition ....................................................................60Operator Precedence and Associativity ................................................................61Using Patterns to Match Digits..............................................................................63An Example: Simple Statistics ..............................................................................64Input and Output ....................................................................................................68

    File Handles and Standard Input and Output ..................................................68Reading a Line from Standard Input with ........................................68Writing to Standard Output with print ..........................................................70printf and sprintf ......................................................................................70

    Another Example: Stocks ......................................................................................72Getting and Verifying the Input........................................................................74Calculating and Printing the Result..................................................................75

    vi Sams Teach Yourself Perl in 21 Days

    00 0355 fm 5/9/02 2:32 PM Page vi

  • A Note About Using Functions ............................................................................76Going Deeper ........................................................................................................77

    Useful Number and String Functions ..............................................................77Bitwise Operators ............................................................................................78The cmp and Operators ............................................................................78Functions and Function-Like Operators ..........................................................79

    Summary ................................................................................................................79Q&A ......................................................................................................................80Workshop ..............................................................................................................81

    Quiz ..................................................................................................................81Exercises ..........................................................................................................81

    Answers..................................................................................................................82Quiz Answers....................................................................................................82Exercise Answers..............................................................................................83

    DAY 4 Working with Lists and Arrays 85

    List Data and Variables ..........................................................................................85Defining and Using Lists and Arrays ....................................................................86

    Creating Lists....................................................................................................87Creating Lists Using the Range Operator ........................................................88Assignment and Lists ......................................................................................89Accessing Array Elements................................................................................90Growing Arrays ................................................................................................91Finding the Length of an Array........................................................................92Sorting Lists and Arrays ..................................................................................92Processing Each Element of an Array..............................................................92Finding the End of an Array ............................................................................93Dealing with the Undefined Value ..................................................................94Deleting Elements from an Array ....................................................................95Testing for the Existence of an Element ..........................................................96

    An Example: More Stats........................................................................................96List and Scalar Context..........................................................................................99

    What Is Context? ..............................................................................................99Finding the Number of Elements in an Array, Revisited ..............................100Context and Assignment ................................................................................101Other Contexts................................................................................................102The scalar Function ....................................................................................103

    Input, Output, and Lists ......................................................................................104Using in list context........................................................................104Printing Lists ..................................................................................................104

    Going Deeper ......................................................................................................105Negative Array Indexes ..................................................................................106More About Ranges........................................................................................106

    Contents vii

    00 0355 fm 5/9/02 2:32 PM Page vii

  • chomp and chop on Lists ..............................................................................106Output Field, Record and List Separators ......................................................107Void Context ..................................................................................................107

    Summary ..............................................................................................................108Q&A ....................................................................................................................109Workshop ............................................................................................................110

    Quiz ................................................................................................................110Exercises ........................................................................................................111

    Answers................................................................................................................111Quiz Answers..................................................................................................111Exercises ........................................................................................................112

    DAY 5 Working with Hashes 115

    Hashes Versus Arrays and Lists ..........................................................................115Defining and Using Hashes ................................................................................117

    List Syntax and Hashes ..................................................................................117Converting Between Arrays, Lists, and Hashes ............................................118Accessing Hash Elements ..............................................................................119Deleting Hash Elements ................................................................................120Processing All the Values in a Hash ..............................................................121Hashes and Context ........................................................................................121

    An Example: Frequencies in the Statistics Program ..........................................122Extracting Data into Arrays or Hashes Using the split Function ..............126

    Another Example: Alphabetical Lists of Names ................................................128A Few More Patterns ..........................................................................................129Yet Another Example: Stock Price Converter ....................................................130Going Deeper ......................................................................................................133Summary ..............................................................................................................134Q&A ....................................................................................................................134Workshop ............................................................................................................135

    Quiz ................................................................................................................135Exercises ........................................................................................................136

    Answers................................................................................................................136Quiz Answers..................................................................................................136Exercises ........................................................................................................137

    DAY 6 Conditionals and Loops 143

    Complex Statements and Blocks ........................................................................144Conditionals ........................................................................................................145

    if, if...else, and if...elsif ................................................................145unless ..............................................................................................................147Conditional Operator ?..: ............................................................................147Using Logical Operators as Conditionals ......................................................148

    viii Sams Teach Yourself Perl in 21 Days

    00 0355 fm 5/9/02 2:32 PM Page viii

  • while Loops........................................................................................................149while..............................................................................................................149until..............................................................................................................151do ....................................................................................................................151

    An Example: Pick a Number ..............................................................................152Iteration with foreach and for Loops ..............................................................156

    foreach ........................................................................................................156for..................................................................................................................158

    Controlling Loops ................................................................................................160last, next, and redo ..................................................................................161Labeling Loops ..............................................................................................162

    Using the $_ (default) Variable............................................................................164Input from Files with while Loops and ........................................................165Going Deeper ......................................................................................................167

    Conditional and Loop Modifiers ....................................................................168Using continue blocks ................................................................................168Constructing switch or case Statements ....................................................169

    Summary ..............................................................................................................169Q&A ....................................................................................................................170Workshop ............................................................................................................171

    Quiz ................................................................................................................171Exercises ........................................................................................................171

    Answers................................................................................................................172Quiz Answers..................................................................................................172Exercise Answers............................................................................................173

    DAY 7 Exploring a Few Longer Examples 175

    Statistics with a Better Histogram ......................................................................176A Number Speller ................................................................................................180Text-to-HTML Converter Script ..........................................................................182

    How It Works..................................................................................................183The Input File ................................................................................................184The Script ......................................................................................................185

    Summary ..............................................................................................................188

    WEEK 2 Doing More 189

    DAY 8 Manipulating Lists and Strings 191

    Array and Hash Slices ........................................................................................192Sorting Lists ........................................................................................................193Searching..............................................................................................................194An Example: More Names ..................................................................................196

    Contents ix

    00 0355 fm 5/9/02 2:32 PM Page ix

  • x Sams Teach Yourself Perl in 21 Days

    Modifying List Elements ....................................................................................201push and pop ................................................................................................201shift and unshift ......................................................................................202splice ..........................................................................................................203

    Other Ways to Mess with Lists............................................................................204reverse ........................................................................................................204join................................................................................................................205map..................................................................................................................205

    Manipulating Strings............................................................................................207reverse ........................................................................................................207index and rindex ........................................................................................208substr ..........................................................................................................208

    Going Deeper ......................................................................................................209Summary ..............................................................................................................210Q&A ....................................................................................................................210Workshop ............................................................................................................211

    Quiz ................................................................................................................211Exercises ........................................................................................................212

    Answers................................................................................................................212Quiz Answers..................................................................................................212Exercise Answers............................................................................................213

    DAY 9 Pattern Matching with Regular Expressions 215

    The Whys and Wherefores of Pattern Matching ................................................216Pattern Matching Operators and Expressions......................................................217Simple Patterns ....................................................................................................218

    Character Sequences ......................................................................................218Matching at Word or Line Boundaries ..........................................................219Matching Alternatives ....................................................................................221

    Matching Groups of Characters ..........................................................................222Character Classes............................................................................................222Ranges ............................................................................................................223Negated Character Classes ............................................................................224Special Classes ..............................................................................................224Matching Any Character with . (Dot) ............................................................225

    Matching Multiple Instances of Characters ........................................................226Optional Characters with ? ............................................................................226Matching Multiple Characters with * ............................................................227Requiring at Least One Instance with + ........................................................228Restricting the Number of Instances ..............................................................228

    00 0355 fm 5/9/02 2:32 PM Page x

  • Contents xi

    An Example: A Guessing Program......................................................................229More About Building Patterns ............................................................................233

    Patterns and Variables ....................................................................................233Patterns and Loops ........................................................................................233

    Another Example: Counting ................................................................................234Pattern Precedence ..............................................................................................235Going Deeper ......................................................................................................236

    More Uses of Patterns ....................................................................................236Pattern Delimiters and Escapes ......................................................................236

    Summary ..............................................................................................................237Q&A ....................................................................................................................238Workshop ............................................................................................................238

    Quiz ................................................................................................................238Exercises ........................................................................................................239

    Answers................................................................................................................239Quiz Answers..................................................................................................239Exercise Answers............................................................................................240

    DAY 10 Doing More with Regular Expressions 243

    Extracting Matches ..............................................................................................243Using Parentheses for Backreferences ..........................................................244Saved Match Variables ..................................................................................246Matches and Context ......................................................................................246A Note About Greed ......................................................................................247

    An Example: Extracting Attributes from HTML Tags........................................249Using Patterns for Search and Replace ..............................................................251More About split ..............................................................................................252Matching Patterns over Multiple Lines ..............................................................253

    Storing Multiple Lines of Input......................................................................253Handling Input with Newlines ......................................................................254

    A Summary of Options and Escapes ..................................................................255An Example: Image Extractor ............................................................................256

    Hints for Building Regular Expressions ........................................................260Going Deeper ......................................................................................................261

    More Metacharacters, Variables, and Options................................................262Summary ..............................................................................................................264Q&A ....................................................................................................................264Workshop ............................................................................................................265

    Quiz ................................................................................................................265Exercises ........................................................................................................266

    Answers................................................................................................................267Quiz Answers..................................................................................................267Exercise Answers............................................................................................268

    00 0355 fm 5/9/02 2:32 PM Page xi

  • xii Sams Teach Yourself Perl in 21 Days

    DAY 11 Creating and Using Subroutines 269

    Subroutines Versus Functions ..............................................................................270Defining and Calling Basic Subroutines ............................................................270

    An Example of a Subroutine ..........................................................................271Defining Subroutines......................................................................................271Calling Subroutines ........................................................................................272

    An Example: Son of Stats....................................................................................273Returning Values from Subroutines ....................................................................275Using Local Variables in Subroutines..................................................................276Passing Values into Subroutines ..........................................................................279

    Passing Arguments ........................................................................................279Handling Arguments Inside Subroutines........................................................280A Note on Arguments Passed by Reference ..................................................281

    Subroutines and Context......................................................................................282Another Example: Stats with a Menu..................................................................282Going Deeper ......................................................................................................289

    Local Variables in Blocks ..............................................................................289Leaving Off the Parentheses for Arguments ..................................................290Using @_ to Pass Arguments to Subroutines..................................................290Anonymous Subroutines ................................................................................291Using Subroutine Prototypes..........................................................................291The caller Function ....................................................................................292

    Summary ..............................................................................................................292Q&A ....................................................................................................................292Workshop ............................................................................................................293

    Quiz ................................................................................................................293Exercises ........................................................................................................294

    Answers................................................................................................................295Quiz Answers..................................................................................................295Exercise Answers............................................................................................296

    DAY 12 Debugging Perl 299

    Using the Debugger: A Simple Example ............................................................300Starting and Running the Debugger ....................................................................305

    Tracing Execution ..........................................................................................306Stepping Through the Script ..........................................................................307Listing the Source ..........................................................................................307Printing Variables ..........................................................................................309Setting Breakpoints ........................................................................................310Other Commands............................................................................................310One Other Thing ............................................................................................311

    00 0355 fm 5/9/02 2:32 PM Page xii

  • Perl Debugger Command Reference ..................................................................311Using a Graphical Debugger ..............................................................................312Going Deeper ......................................................................................................314

    Using Different Debuggers ............................................................................314Running Perl Interactively..............................................................................314Common Pitfalls and FAQs............................................................................315

    Summary ..............................................................................................................315Q&A ....................................................................................................................315Workshop ............................................................................................................315

    Quiz ................................................................................................................315Exercises ........................................................................................................316

    Answers................................................................................................................316Quiz Answers..................................................................................................317Exercise Answers............................................................................................317

    DAY 13 Scope, Modules, and Importing Code 319

    Global Variables and Packages ............................................................................320The Problem with Globals..............................................................................320What’s a Package?..........................................................................................321How Packages and Variables Work ................................................................321A Simple Package Example ..........................................................................322Using Non-Package Global Variables ............................................................323

    Local Scope and Variables ..................................................................................325Local Variables and Local Scope ..................................................................325Local Variables with my and local ..............................................................326

    Using Perl Modules ............................................................................................327Some Terminology ........................................................................................327Getting Modules ............................................................................................328Importing Modules ........................................................................................329Using Modules................................................................................................330Object-Oriented Modules ..............................................................................331Modules from the Inside Out ........................................................................332Importing Symbols by Hand ..........................................................................333Import Tags ....................................................................................................334Using Pragmas................................................................................................335The English Module ....................................................................................336

    An Example: Using the Text::Wrap Module....................................................337Using Modules from CPAN (The Comprehensive Perl Archive Network) ........339

    A Note of Caution ..........................................................................................339Acquiring Modules from CPAN ....................................................................339Installing CPAN Modules on Windows Using PPM......................................340Using Modules from CPAN ..........................................................................341

    Contents xiii

    00 0355 fm 5/9/02 2:32 PM Page xiii

  • Going Deeper ......................................................................................................341Typeglobs........................................................................................................342One Other Difference Between local and my ..............................................343An Example of local Versus my ..................................................................343Package Initialization and Finalization with BEGIN and END ........................345Importing Code with require ......................................................................345

    Summary ..............................................................................................................346Q&A ....................................................................................................................347Workshop ............................................................................................................348

    Quiz ................................................................................................................348Exercises ........................................................................................................349

    Answers................................................................................................................349Quiz Answers..................................................................................................349Exercise Answers............................................................................................350

    DAY 14 Exploring a Few Longer Examples 353

    A Searchable Address Book (address.pl) ......................................................354How It Works..................................................................................................354The Address File ............................................................................................355Inside the Script..............................................................................................356The Code ........................................................................................................361

    A Web Log Processor (weblog.pl) ..................................................................364How It Works..................................................................................................364What a Web Log Looks Like ........................................................................365Building the Script..........................................................................................366The Code ........................................................................................................374

    Summary ..............................................................................................................377

    WEEK 3 Advanced Perl 379

    DAY 15 Working with Files and I/O 381

    Input and Output with File Handles ....................................................................382Creating File Handles with open ..................................................................382The die Function ..........................................................................................384Reading Input from a File Handle..................................................................385Writing Output to a File Handle ....................................................................386Reading and Writing Binary Files..................................................................387Closing a File Handle ....................................................................................387

    An Example: Extract Subjects and Save Them ..................................................388File Tests ..............................................................................................................389A File Test Example ............................................................................................391Working with @ARGV and Script Arguments........................................................393

    Anatomy of the @ARGV ..................................................................................393Script Switches and Fun with Getopt ............................................................394

    xiv Sams Teach Yourself Perl in 21 Days

    00 0355 fm 5/9/02 2:32 PM Page xiv

  • Another Example ................................................................................................398Going Deeper ......................................................................................................399

    More About open and File Handles ..............................................................399Various Other File-Related Functions ............................................................400Expert-Level I/O ............................................................................................400DBM Files ......................................................................................................401Timestamps ....................................................................................................402

    Summary ..............................................................................................................402Q&A ....................................................................................................................403Workshop ............................................................................................................403

    Quiz ................................................................................................................403Exercises ........................................................................................................404

    Answers................................................................................................................405Quiz Answers..................................................................................................405Exercise Answers............................................................................................406

    DAY 16 Using Perl for CGI Scripting 409

    Before You Start ..................................................................................................410How CGI Works ..................................................................................................410Building a CGI Script, From Form to Response ................................................412

    The Form ........................................................................................................412Creating the Script..........................................................................................413

    Testing the Script ................................................................................................415Developing CGI Scripts with CGI.pm ................................................................416

    Using CGI.pm ................................................................................................417Processing Form Input....................................................................................417Generating HTML..........................................................................................418Debugging the Result ....................................................................................420

    An Example: Survey............................................................................................421The Form ........................................................................................................422The Script ......................................................................................................423

    Going Deeper ......................................................................................................427Using CGI Variables ......................................................................................427POST Versus GET ............................................................................................428Redirection......................................................................................................428Cookies and File Upload ................................................................................429CGI Scripts and Security................................................................................429Embedding Perl in Web Servers ....................................................................429

    Summary ..............................................................................................................430Q&A ....................................................................................................................431Workshop ............................................................................................................432

    Quiz ................................................................................................................433Exercises ........................................................................................................433

    Contents xv

    00 0355 fm 5/9/02 2:32 PM Page xv

  • Answers................................................................................................................434Quiz Answers..................................................................................................434Exercise Answers............................................................................................435

    DAY 17 Managing Files and Directories 437

    Managing Files ....................................................................................................437Renaming Files ..............................................................................................438Creating and Following Links ........................................................................438Removing Files and Links..............................................................................439Other Operations ............................................................................................439

    Managing and Navigating Directories ................................................................440Navigating Directories....................................................................................440Listing Files ....................................................................................................441Making and Removing Directories ................................................................443

    An Example: Creating Links ..............................................................................444Going Deeper ......................................................................................................445Summary ..............................................................................................................446Q&A ....................................................................................................................447Workshop ............................................................................................................447

    Quiz ................................................................................................................447Exercises ........................................................................................................448

    Answers................................................................................................................448Quiz Answers..................................................................................................448Exercise Answers............................................................................................449

    DAY 18 Perl and the Operating System 453

    Unix Features in Perl ..........................................................................................454Environment Variables....................................................................................454Running Unix Programs with system ..........................................................455Input with Backquotes....................................................................................456Using Processes: fork, wait, and exec ......................................................457Other Unix-Related Functions........................................................................464

    Perl for Windows ................................................................................................465Compatibility with Unix ................................................................................465Built-in Win32 Subroutines............................................................................466Win32::MsgBox ............................................................................................467Win32 Processes ............................................................................................469Working with the Win32 Registry..................................................................471Other Win32 Modules ....................................................................................473

    Going Deeper ......................................................................................................474Pipes................................................................................................................474Signals ............................................................................................................474Basic Networking ..........................................................................................475Creating User Interfaces with Perl ................................................................475

    xvi Sams Teach Yourself Perl in 21 Days

    00 0355 fm 5/9/02 2:32 PM Page xvi

  • Summary ..............................................................................................................475Q&A ....................................................................................................................476Workshop ............................................................................................................477

    Quiz ................................................................................................................477Exercises ........................................................................................................477

    Answers................................................................................................................478Quiz Answers..................................................................................................478Exercise Answers............................................................................................478

    DAY 19 Working with References 481

    What Is a Reference? ..........................................................................................482The Basics: A General Overview of How to Use References ............................482

    Creating a Reference ......................................................................................483Printing and Using References ......................................................................484Dereferencing References ..............................................................................485Changing Referenced-To Data ......................................................................486

    Using References with Subroutine Arguments and Return Values ....................487Subroutine Arguments ....................................................................................487Passing References Back from Subroutines ..................................................489An Example ....................................................................................................490

    Other Ways of Using References ........................................................................492Dereferencing List Reference Elements ........................................................492References with Blocks ..................................................................................493The ref Function ..........................................................................................494A Note About Memory and Garbage Collection ..........................................495

    Creating Nested Data Structures with References ..............................................496What Is a Nested Data Structure? ..................................................................496Using Anonymous Data..................................................................................497Creating Data Structures with Anonymous Data ..........................................498Other Structures..............................................................................................502

    Building Data Structures with Existing Data ......................................................502Accessing Elements in Nested Data Structures ..................................................504Another Example: A Database of Artists and Their Works ................................505Avoiding the Use of References ..........................................................................510Going Deeper ......................................................................................................511

    Shorthand References to Scalars ....................................................................511Symbolic References ......................................................................................511References to Typeglobs and Filehandles ......................................................512References to Subroutines ..............................................................................513

    Summary ..............................................................................................................513Q&A ....................................................................................................................514Workshop ............................................................................................................515

    Quiz ................................................................................................................515Exercises ........................................................................................................516

    Contents xvii

    00 0355 fm 5/9/02 2:32 PM Page xvii

  • Answers................................................................................................................517Quiz Answers..................................................................................................517Exercise Answers............................................................................................518

    DAY 20 Odds and Ends 523

    Perl One-Liners....................................................................................................524Object-Oriented Programming ............................................................................526

    Getting Started and Learning More................................................................526The Basics (for Those Who Already Know OOP) ........................................527

    An Example: Using Object-Oriented Modules ..................................................534Sockets ................................................................................................................536POD (Plain Old Documentation) Files................................................................539

    Creating POD Files ........................................................................................540Embedding POD in Scripts ............................................................................541

    Evaluating Code On-the-Fly................................................................................541Commonly Used Modules ..................................................................................542

    LWP ................................................................................................................542Sending E-mail with Net::SMTP ..................................................................543Handling XML with Perl................................................................................545

    Creating International Perl Scripts ......................................................................547Script Security with Taint Checking....................................................................548PerlScript..............................................................................................................549What’s Coming in Perl 6 ....................................................................................549Going Deeper ......................................................................................................550Summary ..............................................................................................................550Q&A ....................................................................................................................551Workshop ............................................................................................................552

    Quiz ................................................................................................................552Exercises ........................................................................................................553

    Answers................................................................................................................553Quiz Answers..................................................................................................553Exercise Answers ..........................................................................................555

    DAY 21 Exploring a Few Longer Examples 559

    A Stock Portfolio Manager..................................................................................560The Data File ..................................................................................................560How the Program Works ................................................................................561The Source Code ............................................................................................566

    A Web-Based To Do List (todolist.pl)..........................................................573The Data File ..................................................................................................574How the Script Works ....................................................................................575The Code ........................................................................................................579

    Summary ..............................................................................................................587

    xviii Sams Teach Yourself Perl in 21 Days

    00 0355 fm 5/9/02 2:32 PM Page xviii

  • Appendixes 589

    APPENDIX A Perl Functions 591

    For More Information ..........................................................................................591Perl Functions, in Alphabetical Order ................................................................592

    APPENDIX B Installing Perl on a Unix System 629

    Do You Need to Install Perl? ..............................................................................629Obtaining Perl ......................................................................................................630

    Installing a Vendor Package ..........................................................................630Getting Binaries..............................................................................................631Getting Source (and Related Tools) ..............................................................631

    Extracting and Compiling Perl ............................................................................632Running the Configure Program ....................................................................633Run ..............................................................................................................636

    For More Information ..........................................................................................637

    APPENDIX C Installing Perl for Windows 639

    Downloading Perl for Windows ..........................................................................640Installing Perl for Windows ................................................................................640Running Perl for Windows ..................................................................................642Downloading the Perl Source Code ....................................................................642Getting More Information....................................................................................643

    Index 645

    Contents xix

    00 0355 fm 5/9/02 2:32 PM Page xix

  • About the AuthorsLAURA LEMAY is a member of the gregarious, brightly colored species of computer-bookauthor known as tutorialis prolificus. Although she has been spotted writing in the wildfor numerous years, more public sightings have occurred frequently since 1995, includingseveral versions of Sams Teach Yourself HTML, Sams Teach Yourself Java in 21 Days, andThe Official Marimba Guide to Castanet.

    When not writing books, her primary habitat is in Northern California. Should youencounter her in person, do not make any sudden movements. Further field notes may befound at http://www.lne.com/lemay/.

    RAFE COLBURN is a programmer and author working in North Carolina. His previousbooks include Sams Teach Yourself CGI in 24 Hours and Special Edition Using SQL. Healso has a Web site at http://rc3.org that he updates often, and can be reached [email protected].

    00 0355 fm 5/9/02 2:32 PM Page xx

  • AcknowledgmentsTo Larry Wall, for writing Perl.

    To the excellent Perl programmers who reviewed this book—J. Eric Townsend, RafeColburn, Chris Spurgeon, and Ian McKallen—for being so good at finding my mistakesand confusions and offering helpful suggestions for “Other Ways To Do It.”

    To the perl.ind conference on the WeLL—ditto.

    To all the nice folks at Sams Publishing for being very patient indeed during the writingof this book.

    And to Eric, for everything, not the least of which was introducing me to Perl a long,long time ago.

    —Laura Lemay

    I’d like to thank the staff at Sams for their patience, support, and encouragement. And, asalways, I’d like to thank my wife—she’s a rock.

    —Rafe Colburn

    00 0355 fm 5/9/02 2:32 PM Page xxi

  • Tell Us What You Think!As the reader of this book, you are our most important critic and commentator. We valueyour opinion and want to know what we’re doing right, what we could do better, whatareas you’d like to see us publish in, and any other words of wisdom you’re willing topass our way.

    I welcome your comments. You can e-mail or write me directly to let me know what youdid or didn’t like about this book—as well as what we can do to make our booksstronger.

    Please note that I cannot help you with technical problems related to the topic of thisbook, and that due to the high volume of mail I receive, I might not be able to reply toevery message.

    When you write, please be sure to include this book’s title and author as well as yourname and phone or fax number. I will carefully review your comments and share themwith the author and editors who worked on the book.

    E-Mail: [email protected]

    Mail: Mark TaberAssociate PublisherSams Publishing800 Easty 96th StreetIndianapolis, IN 46240 USA

    00 0355 fm 5/9/02 2:32 PM Page xxii

  • IntroductionA long time ago at a workstation manufacturer far, far away, a young writer was learninghow to program sed and awk scripts on Unix systems. This was before there was a SamsTeach Yourself Unix, so I learned Unix scripting the old-fashioned, time-honored way:trial and error, sketchy online documentation, copying other people’s scripts, and askinga lot of questions. Particularly asking a lot of questions. Each time I got stuck I wouldsend e-mail to my various Unix-proficient friends, and each time I would get a patientreply carefully pointing out what I was doing wrong. In addition to the advice, however,nearly every e-mail started with “You should use Perl to do that.”

    It seemed that no matter what I wanted to do, the answer always included “you shoulduse Perl to do that.” Eventually, I got the hint, abandoned the hodgepodge of Unix pro-grams I was working with, and learned Perl. And now I can’t imagine using anythingelse.

    “You should use Perl to do that” could easily be the motto of the Perl language (exceptthat it already has a number of mottoes). Perl is the duct tape of programmer tools; itmight not be the best solution to any particular problem, but it’s certainly capable andpretty darn useful for just about any problem. Quick to use, quick to run, quick tochange, you can often hack together a solution to a problem in Perl faster than it wouldtake a C++ IDE to start up.

    And you accomplish these solutions not just on a Unix system—Perl runs on a wide vari-ety of platforms including Windows and Mac, and is just as useful on those GUI-centricplatforms as it is on a more command line–centric system such as Unix. Use the Web?Perl is one of the most popular languages (and arguably the standard) for writing CGIscripts and for maintaining Web servers.

    However, before you can use Perl, you have to learn it. Perl is a mishmash of variousUnix tools, shell scripting, C, and occasional object-oriented features. That’s where SamsTeach Yourself Perl in 21 Days comes in. This book is a gentle but thorough introductionto the Perl language and how it can be used. If you’re a beginning programmer, or if youhave some background, you’ll learn the basics and build on them as the book progresses.If you’re an experienced programmer, you might find the first few chapters easy going,but there’s plenty of content later to challenge even a veteran. In either case, by the timeyou finish this book you will have a near-complete grasp of the entirety of the Perl lan-guage and how to use it.

    01 0355 intro 5/9/02 2:32 PM Page 1

  • 2 Sams Teach Yourself Perl in 21 Days, Second Edition

    How This Book Is OrganizedThis book is split into 21 lessons and three weeks. Each week covers a variety of topics,growing in complexity, and building on the lessons before it.

    Each lesson describes a topic and contains two or three examples that illustrate eachtopic. At the end of each lesson, you get a chance to apply what you’ve learned withquizzes and exercises (and the answers to those quizzes also appear at the end of eachlesson). On the final day of each week, we’ll pause for a day to explore some longer,more useful examples in Perl, to review what you’ve learned in the previous week andshow how larger scripts can be built.

    The lessons in Sams Teach Yourself Perl in 21 Days include the following:

    Day 1, “An Introduction to Perl,” is the basic background to what Perl is, what it does,how it works, and how to get started using it.

    Day 2, “Working with Strings and Numbers (Scalar Data),” introduces scalar data, thebasic building blocks in the language, and some simple operators for using them.

    Day 3, “More Scalar Data and Operators,” finishes up what we started on Day 2, withmore detail on the various ways you can manipulate numbers and strings. You’ll also geta basic introduction to input and output in this lesson.

    Day 4, “Working with Lists and Arrays,” shows how to create and manipulate groups ofdata.

    Day 5, “Working with Hashes,” expands on the information from the last lesson with anexploration of hashes (also called associative arrays or keyed lists).

    Day 6, “Conditionals and Loops,” moves from the subject of data to program flow. Thischapter covers conditionals (if statements) and loops (while and for) as well as similarconstructs.

    Day 7, “Exploring a Few Longer Examples,” is the first of our longer-example lessons.Here, we’ll look at three examples that make use of what you’ve learned so far.

    Day 8, “Manipulating Lists and Strings,” explores some of the various ways in whichPerl can be used to manipulate data stored in either a list (an array or hash) or in a string.This includes searching, sorting, extracting, or adding elements, or processing all the ele-ments in some way.

    Day 9, “Pattern Matching with Regular Expressions,” is the first of two chapters explor-ing one of Perl’s most powerful features, regular expressions, which allow you to createand match patterns of characters in data.

    01 0355 intro 5/9/02 2:32 PM Page 2

  • Day 10, “Doing More with Regular Expressions,” expands on what you learned the daybefore with more detail about extracting and replacing data matched by patterns, as wellas building more complex patterns.

    Day 11, “Creating and Using Subroutines,” delves into creating subroutines (sometimescalled functions or procedures) to allow reusable code.

    Chapter 12, “Debugging Perl,” is a bit of a sideline from the description of the core lan-guage. In this chapter we’ll look at the source-level debugger that can help you trackdown subtle problems in your code.

    Chapter 13, “Scope, Modules, and Importing Code,” collects several issues surroundingglobal and local variables, compile-time versus runtime execution, and the use of codelibraries, called modules.

    Chapter 14, “Exploring a Few Longer Examples,” is the second of the longer examplechapters.

    Day 15, “Working with Files and I/O,” expands on the simple input and output you’velearned in the previous parts of the book. You explore working more directly with fileson the computer’s file system and doing more with getting input into a script and out-putting data from that script.

    Day 16, “Using Perl for CGI Scripting,” explores how to use Perl specifically for creat-ing Web server–based CGI scripts.

    Day 17, “Managing Files and Directories,” is an extension of the chapter on file inputand output; this chapter explores how to work with file systems, including navigatingdirectory hierarchies and renaming and moving files.

    Day 18, “Perl and the Operating System,” explores several features of Perl that are spe-cific to particular platforms. Much of Perl was developed for Unix and continues to beUnix-centric; the Windows version of Perl has libraries that take advantage of specificfeatures of the platform. This lesson explores those platform-specific features.

    Day 19, “Working with References,” explores one of the more advanced features ofPerl—the use of references, which allow more efficient data management and more com-plex nested data structures.

    Day 20, “Odds and Ends,” finishes up the book with a summary of the few features ofPerl that weren’t covered in the rest of the book.

    Day 21, “Exploring a Few Longer Examples,” is the last of the longer example chapters.

    Introduction 3

    01 0355 intro 5/9/02 2:32 PM Page 3

  • Conventions Used in This BookAny word or term that appears on your screen is presented in a monospaced font tomimic the way it looks on your screen:

    it will look like this

    Text that you should type is presented in a bold monospaced font:

    type in text that looks like this

    Placeholders for variables and expressions are presented in monospaced italic type.

    4 Sams Teach Yourself Perl in 21 Days, Second Edition

    A Note presents interesting, sometimes technical pieces of information relat-ed to the surrounding discussion.

    Note

    A Tip offers advice or offers an easier way to do something.Tip

    A Caution advises you of potential problems and helps you steer clear of disaster.

    Caution

    01 0355 intro 5/9/02 2:32 PM Page 4

  • Getting StartedDay 1 An Introduction to Perl

    Day 2 Working with Strings and Numbers (Scalar Data)

    Day 3 More Scalar Data and Operators

    Day 4 Working with List s and Arrays

    Day 5 Working with Hashes

    Day 6 Conditionals and Loops

    Day 7 Exploring a Few Longer Examples

    WEEK 1 1

    2

    3

    4

    5

    6

    7

    02 0355 part01 5/9/02 2:32 PM Page 5

  • 02 0355 part01 5/9/02 2:32 PM Page 6

  • DAY 1

    WEEK 1

    An Introduction to PerlGreetings and welcome to Sams Teach Yourself Perl in 21 Days! Today, and forthe next 20 days, I’ll be your guide to all things Perl. By the time you finishthis book—or at least by the time you put it down—you should know enoughPerl to accomplish just about anything you’d like to do, and to converse intelli-gently with other Perl programmers.

    Today we’re going to start with some basic information to ease you into work-ing with Perl. Today’s lesson is kind of short; just enough to give you a littlebackground and to get you started with some simple Perl scripts. In particular,you will

    • Learn some background on Perl: what it is, who created it, who’s workingon it now.

    • Find out why you should learn Perl (reasons besides “my boss told me to.”)

    • Explore some actual Perl code, so you can get an idea about how Perl iswritten and run (and be prepared for the rest of this week’s lessons).

    And so, without further ado, let’s get started. Week one, Chapter one, sectionone—Onward!

    03 0355 ch01 5/9/02 2:32 PM Page 7

  • What Is Perl and Where Did It Come From?Perl is not a typo for pearl. Perl is an acronym. It stands for Practical Extraction andReport Language, which is a pretty good description of what Perl does particularly well.Extraction for looking at files and pulling out the important parts (for example, the actualtext data from an HTML file, or the user or hostnames from a networking log file); andreport for generating output and, well, reports, based on the information that was extracted.It’s a practical language because it’s much easier to write these sorts of programs quicklyin Perl than it would be in a language such as C.

    Perl was created in 1987 by Larry Wall, who at the time was already well known in theUnix-software world for having written the freely available patch program as well as theUsenet newsreader rn. The story goes that Larry was working on a task for which the Unixprogram awk (the popular extraction and report language of the time) wasn’t powerfulenough, but he realized the task would take a whole lot of work to accomplish in a languagesuch as C. So Perl was created as a scripting language that borrows bits from variousother Unix tools and languages, such as sed, grep, awk, shell scripting, and, yes, C. Also,as with patch and rn, Perl was released for free to the Unix community. And the Unixcommunity approved.

    For many years, Perl was the language of choice for Unix system administrators and otherUnix programmers who needed a flexible, quick-to-program language to accomplishtasks for which a language such as C would be overkill (or take too much work), or fortasks that were too complex for shell scripting. It was because of its existing popularityas a Unix language that Perl became popular as a Web language for creating CGI scripts.CGI (Common Gateway Interface), originally developed on Unix for Unix Web servers,allowed programs and scripts to be run on Web servers in response to HTML forms orother input from Web pages. Perl fit neatly into that niche, and as the Web and CGI grewmore popular, so did Perl. As Web servers and tools spread to systems other than Unix, sodid Perl, and these days you can get Perl for just about any computer or operating systemout there, for use with Web development or as a general-purpose programming language.Larry Wall originally “owned” Perl and was responsible for keeping it updated and incor-porating new changes. These days, with Perl a much larger program and much harder to maintain, the task of updating and maintaining Perl now falls to a close-knit group ofvolunteer programmers. These programmers, including Larry Wall, maintain the core Perlsource, port the source to platforms other than Unix, coordinate bug fixes, and establishthe “standard” Perl release (the Authors file in the standard Perl distribution lists the pri-mary dramatis personae of Perl). No single organization owns Perl; like the GNU tools(GNU emacs, GCC, GDB, and so on) and the Linux operating system; Perl is definedand managed on a volunteer, goodwill basis. It’s also available free of charge; all youhave to do is download and install it.

    8 Day 1

    03 0355 ch01 5/9/02 2:32 PM Page 8

  • An Introduction to Perl 9

    1The current major version of Perl is Perl 5, and it is the version this book covers. All Perlreleases also have minor versions with various numbers and letters, which most commonlyfix bugs that were found in the original release (although some new features do creepinto the minor version releases). The current Unix and Windows version of Perl as Iwrite this book is 5.6.1. If you are running Mac OS X Perl 5.6 is included as a standardcomponent.

    These minor numbers might have changed by the time you read this, as work is ongoingon all the Perl ports (and at any time, there might be separate releases for less stable betaversions as well as the current “official” version). For the most part, however, the minorversion is less important than making sure you have some version of Perl 5 installed.

    If you are running Mac OS X, you are running a flavor of Unix and Perl thatbehaves as if it were running on a Unix system. Follow along with the Unixdirections using the command promt from the Terminal.app.

    Note

    Why Learn Perl?There are an enormous number of programming languages available on the market today,all of which seem to claim to be able to solve all your problems in half the time, at aquarter of the cost, and then bring about world peace, too. So why learn Perl over anotherone of those vaunted languages?

    The best reason is that different tools work best for different tasks, and Perl is particu-larly good at a number of common tasks. But there are a number of other good reasonsto learn and use Perl.

    Perl Is UsefulHow’s that for a good reason? Perl is probably the language for you if any of the followingprofiles describe you.

    • You’re a system administrator looking for a general-purpose scripting language

    • You’re a Web programmer with a dozen CGI programs that your Web designerswant you to write

    • You’re a fairly well-versed Unix user looking to expand your knowledge

    • You’re a programmer looking to quickly prototype a more complicated program

    • You just want a language that will enable you to hack around with stuff

    You can do real work in Perl, and you can get it done right away.

    03 0355 ch01 5/9/02 2:32 PM Page 9

  • Perl Doesn’t Need Any Fancy SoftwareTo use Perl, you do not need to buy a nifty shrink-wrapped Perl program. You don’t needa Perl compiler or an integrated Perl development environment. You don’t need a browserthat supports Perl or a computer that says “Perl Inside.” All you need is one thing: thestandard Perl interpreter. You can get that for free, simply by downloading it. Okay, thereis one other thing you need: You must have a text editor in which to write your Perlscripts. One of these comes with every system you can run Perl on, so you’re still safe.

    You Can Program Perl QuicklyPerl is a scripting language, which means that your Perl scripts are just text files, and they’reexecuted on the fly when Perl runs them. You don’t have to use a compiler to convertyour code to some other format like an executable or a bytecode file, as you would for alanguage such as C or Java. This makes Perl quicker to get running for initial programs,makes the debugging process faster, and also allows you to modify your Perl scriptsquicker and easier than in C.

    10 Day 1

    Scripting languages are often called interpreted languages in ComputerScience parlance. Although Perl might appear to be an interpreted languagebecause its programs are scripts and the Perl interpreter runs those scripts,Perl is actually both a compiled and interpreted language.

    When it operates on a script, Perl reads in the whole thing, parses it for syntax,compiles it, and then executes the result. Although this gives Perl scripts theappearance of being interpreted, and you can modify and rerun Perl scriptsright away as you can with an interpreted language, it also gives you somemeasure of control over the compilation process. Perl also runs faster than apure interpreted language does (although not as fast as a compiled language).

    Note

    Perl Is PortableBecause Perl is a scripting language, a Perl script is a Perl script is a Perl script regardlessof which platform you run it on. Although there are differences in Perl on different plat-forms, and features that only work on some platforms (I’ll point those out as we run acrossthem), in many