Learning Perl. 5Th Edition [PDF]
Total Page:16
File Type:pdf, Size:1020Kb
Learning Perl ,perlroadmap.24755 Page ii Tuesday, June 17, 2008 8:15 AM Other Perl resources from O’Reilly Related titles Advanced Perl Programming Perl Debugger Pocket Intermediate Perl Reference Mastering Perl Perl in a Nutshell Perl 6 and Parrot Essentials Perl Testing: A Developer’s Perl Best Practices Notebook Perl Cookbook Practical mod-perl Perl Books perl.oreilly.com is a complete catalog of O’Reilly’s books on Perl Resource Center and related technologies, including sample chapters and code examples. Perl.com is the central web site for the Perl community. It is the perfect starting place for finding out everything there is to know about Perl. Conferences O’Reilly brings diverse innovators together to nurture the ideas that spark revolutionary industries. We specialize in document- ing the latest tools and systems, translating the innovator’s knowledge into useful skills for those in the trenches. Visit conferences.oreilly.com for our upcoming events. Safari Bookshelf (safari.oreilly.com) is the premier online refer- ence library for programmers and ITprofessionals. Conduct searches across more than 1,000 books. Subscribers can zero in on answers to time-critical questions in a matter of seconds. Read the books on your Bookshelf from cover to cover or sim- ply flip to the page you need. Try it today with a free trial. main.title Page iii Monday, May 19, 2008 11:21 AM FIFTH EDITION LearningTomcat Perl™ The Definitive Guide Randal L. Schwartz,Jason Tom Brittain Phoenix, and and Ian brian F. Darwin d foy Beijing • Cambridge • Farnham • Köln • Sebastopol • Taipei • Tokyo Learning Perl, Fifth Edition by Randal L. Schwartz, Tom Phoenix, and brian d foy Copyright © 2008 O’Reilly Media. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://safari.oreilly.com). For more information, contact our corporate/ institutional sales department: (800) 998-9938 or [email protected]. Editor: Andy Oram Indexer: Ellen Troutman Zaig Production Editor: Loranah Dimant Cover Designer: Karen Montgomery Copyeditor: Loranah Dimant Interior Designer: David Futato Proofreader: Sada Preisch Illustrator: Jessamyn Read Printing History: November 1993: First Edition. July 1997: Second Edition. July 2001: Third Edition. July 2005: Fourth Edition. July 2008: Fifth Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Learning Perl, the image of a llama, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information con- tained herein. ISBN: 978-0-596-52010-6 [M] 1213729146 Table of Contents Preface ..................................................................... xi 1. Introduction ............................................................ 1 Questions and Answers 1 What Does “Perl” Stand For? 4 How Can I Get Perl? 8 How Do I Make a Perl Program? 12 A Whirlwind Tour of Perl 16 Exercises 17 2. Scalar Data ............................................................ 19 Numbers 19 Strings 22 Perl’s Built-in Warnings 26 Scalar Variables 27 Output with print 29 The if Control Structure 33 Getting User Input 34 The chomp Operator 35 The while Control Structure 36 The undef Value 36 The defined Function 37 Exercises 38 3. Lists and Arrays ........................................................ 39 Accessing Elements of an Array 40 Special Array Indices 41 List Literals 41 List Assignment 43 Interpolating Arrays into Strings 46 The foreach Control Structure 47 Scalar and List Context 49 v <STDIN> in List Context 52 Exercises 54 4. Subroutines ........................................................... 55 Defining a Subroutine 55 Invoking a Subroutine 56 Return Values 56 Arguments 58 Private Variables in Subroutines 60 Variable-Length Parameter Lists 60 Notes on Lexical (my) Variables 63 The use strict Pragma 64 The return Operator 65 Nonscalar Return Values 67 Persistent, Private Variables 68 Exercises 69 5. Input and Output ....................................................... 71 Input from Standard Input 71 Input from the Diamond Operator 73 The Invocation Arguments 75 Output to Standard Output 76 Formatted Output with printf 79 Filehandles 81 Opening a Filehandle 83 Fatal Errors with die 86 Using Filehandles 88 Reopening a Standard Filehandle 90 Output with say 90 Exercises 91 6. Hashes ................................................................ 93 What Is a Hash? 93 Hash Element Access 96 Hash Functions 100 Typical Use of a Hash 103 The %ENV hash 104 Exercises 105 7. In the World of Regular Expressions ...................................... 107 What Are Regular Expressions? 107 Using Simple Patterns 108 Character Classes 113 vi | Table of Contents Exercises 115 8. Matching with Regular Expressions ....................................... 117 Matches with m// 117 Option Modifiers 118 Anchors 120 The Binding Operator, =~ 121 Interpolating into Patterns 122 The Match Variables 123 General Quantifiers 129 Precedence 130 A Pattern Test Program 132 Exercises 132 9. Processing Text with Regular Expressions ................................. 135 Substitutions with s/// 135 The split Operator 138 The join Function 139 m// in List Context 140 More Powerful Regular Expressions 140 Exercises 147 10. More Control Structures ................................................ 149 The unless Control Structure 149 The until Control Structure 150 Expression Modifiers 151 The Naked Block Control Structure 152 The elsif Clause 153 Autoincrement and Autodecrement 154 The for Control Structure 155 Loop Controls 158 The Ternary Operator, ?: 162 Logical Operators 164 Exercises 168 11. Perl Modules .......................................................... 169 Finding Modules 169 Installing Modules 170 Using Simple Modules 171 Exercise 177 12. File Tests ............................................................. 179 File Test Operators 179 Table of Contents | vii The stat and lstat Functions 186 The localtime Function 187 Bitwise Operators 188 Exercises 189 13. Directory Operations ................................................... 191 Moving Around the Directory Tree 191 Globbing 192 An Alternate Syntax for Globbing 193 Directory Handles 194 Recursive Directory Listing 195 Manipulating Files and Directories 195 Removing Files 196 Renaming Files 197 Links and Files 198 Making and Removing Directories 203 Modifying Permissions 205 Changing Ownership 205 Changing Timestamps 206 Exercises 206 14. Strings and Sorting .................................................... 209 Finding a Substring with index 209 Manipulating a Substring with substr 210 Formatting Data with sprintf 212 Advanced Sorting 214 Exercises 219 15. Smart Matching and given-when ........................................ 221 The Smart Match Operator 221 Smart Match Precedence 224 The given Statement 225 when with Many Items 229 Exercises 230 16. Process Management .................................................. 233 The system Function 233 The exec Function 236 The Environment Variables 237 Using Backquotes to Capture Output 238 Processes as Filehandles 241 Getting Down and Dirty with Fork 243 Sending and Receiving Signals 244 viii | Table of Contents Exercises 246 17. Some Advanced Perl Techniques ......................................... 249 Trapping Errors with eval 249 Picking Items from a List with grep 252 Transforming Items from a List with map 253 Unquoted Hash Keys 254 Slices 254 Exercise 259 A. Exercise Answers ...................................................... 261 B. Beyond the Llama ..................................................... 295 Index ..................................................................... 315 Table of Contents | ix Preface Welcome to the fifth edition of Learning Perl, updated for Perl 5.10 and its latest fea- tures. This book is good even if you are still using Perl 5.6 (although, it’s been a long time since it was released; have you thought about upgrading?). If you’re looking for the best way to spend your first 30 to 45 hours with the Perl programming language, you’ve found it. In the pages that follow, you’ll find a carefully paced introduction to the language that is the workhorse of the Internet, as well as the language of choice for system administrators, web hackers, and casual programmers around the world. We can’t give you all of Perl in just a few hours. The books that promise that are probably fibbing a bit. Instead, we’ve carefully selected a useful subset of Perl for you to learn, good for programs from 1 to 128 lines long, which end up being about 90% of the programs in use out there. And when you’re ready to go on, you can get Inter- mediate Perl, which picks up where this book leaves off. We’ve also included a number of pointers for further education. Each chapter is small enough so you can read it in an hour or two. Each chapter ends with a series of