Learning Rl E P - CuteBoyProgrammers

Transcription

7thEditionLearningPerlMAKING EASY THINGS EASY ANDHARD THINGS POSSIBLERandal L. Schwartz,brian d foy &Tom Phoenix

SEVENTH EDITIONLearning PerlMaking Easy Things Easy andHard Things PossibleRandal L. Schwartz, brian d foy, and Tom PhoenixBeijingBoston Farnham SebastopolTokyo

Learning Perlby Randal L. Schwartz, brian d foy, and Tom PhoenixCopyright 2017 Randal L. Schwartz, brian foy, and Tom Phoenix. 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 arealso available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐tutional sales department: 800-998-9938 or corporate@oreilly.com.Editor: Heather SchererProduction Editor: Melanie YarbroughCopyeditor: Jasmine KwitynProofreader: Sonia SarubaOctober 2016:Indexer: Lucie HaskinsInterior Designer: David FutatoCover Designer: Karen MontgomeryIllustrator: Rebecca DemarestSeventh EditionRevision History for the Seventh Edition2016-10-05: First Release2018-03-02: Second ReleaseSee http://oreilly.com/catalog/errata.csp?isbn 9781491954324 for release details.The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Perl, the cover image, andrelated trade dress are trademarks of O’Reilly Media, Inc.While the publisher and the authors have used good faith efforts to ensure that the information andinstructions contained in this work are accurate, the publisher and the authors disclaim all responsibilityfor errors or omissions, including without limitation responsibility for damages resulting from the use ofor reliance on this work. Use of the information and instructions contained in this work is at your ownrisk. If any code samples or other technology this work contains or describes is subject to open sourcelicenses or the intellectual property rights of others, it is your responsibility to ensure that your usethereof complies with such licenses and/or rights.978-1-491-95432-4[LSI]

Table of ContentsPreface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Questions and AnswersIs This the Right Book for You?What About the Exercises and Their Answers?What If I’m a Perl Course Instructor?What Does “Perl” Stand For?Why Did Larry Create Perl?Why Didn’t Larry Just Use Some Other Language?Is Perl Easy or Hard?How Did Perl Get to Be So Popular?What’s Happening with Perl Now?What’s Perl Really Good For?What Is Perl Not Good For?How Can I Get Perl?What Is CPAN?Is There Any Kind of Support?What If I Find a Bug in Perl?How Do I Make a Perl Program?A Simple ProgramWhat’s Inside That Program?How Do I Compile My Perl Program?A Whirlwind Tour of PerlExercises112344457778899101011131516172. Scalar Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19Numbers19iii

All Numbers Have the Same Format InternallyInteger LiteralsNondecimal Integer LiteralsFloating-Point LiteralsNumeric OperatorsStringsSingle-Quoted String LiteralsDouble-Quoted String LiteralsString OperatorsAutomatic Conversion Between Numbers and StringsPerl’s Built-In WarningsInterpreting Nondecimal NumeralsScalar VariablesChoosing Good Variable NamesScalar AssignmentCompound Assignment OperatorsOutput with printInterpolation of Scalar Variables into StringsCreating Characters by Code PointOperator Precedence and AssociativityComparison OperatorsThe if Control StructureBoolean ValuesGetting User InputThe chomp OperatorThe while Control StructureThe undef ValueThe defined 23233343637373839404041413. Lists and Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Accessing Elements of an ArraySpecial Array IndicesList LiteralsThe qw ShortcutList AssignmentThe pop and push OperatorsThe shift and unshift OperatorsThe splice OperatorInterpolating Arrays into StringsThe foreach Control StructurePerl’s Favorite Default: iv Table of Contents4445454647494950515253

The reverse OperatorThe sort OperatorThe each OperatorScalar and List ContextUsing List-Producing Expressions in Scalar ContextUsing Scalar-Producing Expressions in List ContextForcing Scalar Context STDIN in List ContextExercises5354545556585858594. Subroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Defining a SubroutineInvoking a SubroutineReturn ValuesArgumentsPrivate Variables in SubroutinesVariable-Length Parameter ListsA Better &max RoutineEmpty Parameter ListsNotes on Lexical (my) VariablesThe use strict PragmaThe return OperatorOmitting the AmpersandNonscalar Return ValuesPersistent, Private VariablesSubroutine 85. Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Input from Standard InputInput from the Diamond OperatorThe Double DiamondThe Invocation ArgumentsOutput to Standard OutputFormatted Output with printfArrays and printfFilehandlesOpening a FilehandleBinmoding FilehandlesBad FilehandlesClosing a FilehandleFatal Errors with die81838585868991919396969797Table of Contents v

Warning Messages with warnAutomatically die-ingUsing FilehandlesChanging the Default Output FilehandleReopening a Standard FilehandleOutput with sayFilehandles in a ScalarExercises99991001001011021021046. Hashes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107What Is a Hash?Why Use a Hash?Hash Element AccessThe Hash as a WholeHash AssignmentThe Big ArrowHash FunctionsThe keys and values FunctionsThe each FunctionTypical Use of a HashThe exists FunctionThe delete FunctionHash Element InterpolationThe %ENV 181181197. Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121SequencesPractice Some PatternsThe WildcardQuantifiersGrouping in PatternsAlternationCharacter ClassesCharacter Class ShortcutsNegating the ShortcutsUnicode PropertiesAnchorsWord AnchorsExercisesvi Table of Contents121123125126130133134135137137138139141

8. Matching with Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143Matches with m//Match ModifiersCase-Insensitive Matching with /iMatching Any Character with /sAdding Whitespace with /xCombining Option ModifiersChoosing a Character InterpretationBeginning and End-of-Line AnchorsOther OptionsThe Binding Operator The Match VariablesThe Persistence of CapturesNoncapturing ParenthesesNamed CapturesThe Automatic Match VariablesPrecedenceExamples of PrecedenceAnd There’s MoreA Pattern Test 511521531551571581581591599. Processing Text with Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161Substitutions with s///Global Replacements with /gDifferent DelimitersSubstitution ModifiersThe Binding OperatorNondestructive SubstitutionsCase ShiftingMetaquotingThe split OperatorThe join Functionm// in List ContextMore Powerful Regular ExpressionsNongreedy QuantifiersFancier Word BoundariesMatching Multiple-Line TextUpdating Many FilesIn-Place Editing from the Command 69170172172174176Table of Contents vii

10. More Control Structures. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177The unless Control StructureThe else Clause with unlessThe until Control StructureStatement ModifiersThe Naked Block Control StructureThe elsif ClauseAutoincrement and AutodecrementThe Value of AutoincrementThe for Control StructureThe Secret Connection Between foreach and forLoop ControlsThe last OperatorThe next OperatorThe redo OperatorLabeled BlocksThe Conditional OperatorLogical OperatorsThe Value of a Short-Circuit OperatorThe defined-or OperatorControl Structures Using Partial-Evaluation 618618718818919019119219319419611. Perl Modules. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Finding ModulesInstalling ModulesUsing Your Own DirectoriesUsing Simple ModulesThe File::Basename ModuleUsing Only Some Functions from a ModuleThe File::Spec ModulePath::ClassDatabases and DBIDates and TimesExercises19719819920120220320420520520620712. File Tests. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209File Test OperatorsTesting Several Attributes of the Same FileStacked File Test OperatorsThe stat and lstat FunctionsThe localtime Functionviii Table of Contents209213214216217

Bitwise OperatorsUsing BitstringsExercises21821922213. Directory Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223The Current Working DirectoryChanging the DirectoryGlobbingAn Alternate Syntax for GlobbingDirectory HandlesManipulating Files and DirectoriesRemoving FilesRenaming FilesLinks and FilesMaking and Removing DirectoriesModifying PermissionsChanging OwnershipChanging 3923924024014. Strings and Sorting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243Finding a Substring with indexManipulating a Substring with substrFormatting Data with sprintfUsing sprintf with “Money Numbers”Advanced SortingSorting a Hash by ValueSorting by Multiple KeysExercises24324524624724825225325415. Process Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255The system FunctionAvoiding the ShellThe Environment VariablesThe exec FunctionUsing Backquotes to Capture OutputUsing Backquotes in a List ContextExternal Processes with IPC::System::SimpleProcesses as FilehandlesGetting Down and Dirty with ForkSending and Receiving able of Contents ix

16. Some Advanced Perl Techniques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275SlicesArray SliceHash SliceKey-Value SlicesTrapping ErrorsUsing evalMore Advanced Error HandlingPicking Items from a List with grepTransforming Items from a List with mapFancier List 1A. Exercise Answers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293B. Beyond the Llama. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329C. A Unicode Primer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339D. Experimental Features. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357x Table of Contents

PrefaceWelcome to the seventh edition of Learning Perl, updated for Perl 5.24 and its latestfeatures. This book is still mostly good even if you are still using Perl 5.8 (although,it’s been a long time since it was released; have you thought about upgrading?).We hope you’re reading this preface before you buy the book because there’s a histori‐cal hiccup that may cause some confusion. There’s another language, Perl 6, thatstarted off as a replacement for Perl 5 but then went out on its own without changingthe name. As we write this, Perl 5 is probably the version you want. It’s the widelyinstalled and used language that people mean when they say simply “Perl.” It’s the oneyou want if you don’t know why this paragraph is here.If you’re looking for the best way to spend your first 30 to 45 hours with the Perl pro‐gramming language, you’ve found it. In the pages that follow, you’ll find a carefullypaced introduction to the language that is the workhorse of the Internet, as well as thelanguage of choice for system administrators, web hackers, and casual programmersaround the world. We’ve designed this book based on the in-person classes we teach,so we’ve timed the book for a week’s worth of work.We can’t give you all of Perl in just a few hours. The books that promise that are prob‐ably fibbing a bit. Instead, we’ve carefully selected a useful subset of Perl for you tolearn, good for programs from 1 to 128 lines long, which end up being about 90% ofthe 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 numberof pointers for further education.Each chapter is small enough so you can read it in an hour or two. Each chapter endswith a series of exercises to help you practice what you’ve just learned, with theanswers in Appendix A for your reference. Thus, this book is ideally suited for aclassroom “Introduction to Perl” course. We know this directly because the materialfor this book was lifted almost word for word from our flagship “Learning Perl”course, delivered to thousands of students around the world. However, we’vedesigned the book for self-study as well.xi

Perl lives as the “toolbox for Unix,” but you don’t have to be a Unix guru, or even aUnix user, to read this book. Unless otherwise noted, everything we’re saying appliesequally well to Windows ActivePerl from ActiveState and Strawberry Perl and prettymuch every other modern implementation of Perl.Although you don’t need to know a single thing about Perl to begin reading this book,we recommend that you already have familiarity with basic programming conceptssuch as variables, loops, subroutines, and arrays, and the all-important “editing asource code file with your favorite text editor.” We don’t spend any time trying toexplain those concepts. Although we’re pleased that we’ve had many reports of peoplesuccessfully picking up Learning Perl and grasping Perl as their first programminglanguage, of course we can’t promise the same results for everyone.Typographical ConventionsThe following font conventions are used in this book:Constant widthUsed for method names, function names, variables, and attributes. It is also usedfor code examples.Constant width boldUsed to indicate user input.Constant width italicUsed to indicate a replaceable item in code (e.g., filename, where you are sup‐posed to substitute an actual filename).ItalicUsed for filenames, URLs, hostnames, commands in text, important words onfirst mention, and emphasis.[37]At the start of an exercise’s text, we provide a (very rough) estimate of how manyminutes you can expect to spend on that particular exercise.Code ExamplesThis book is here to help you get your job done. You are invited to copy the code inthe book and adapt it for your own needs. Rather than copying by hand, however, weencourage you to download the code from the book’s companion website.xii Preface

In general, you may use the code in this book in your programs and documentation.You do not need to contact us for permission unless you’re reproducing a significantportion of the code. For example, writing a program that uses several chunks of codefrom this book does not require permission. Selling or distributing a CD-ROM ofexamples from O’Reilly books does require permission. Answering a question by cit‐ing this book and quoting example code does not require permission. Incorporating asignificant amount of example code from this book into your product’s documenta‐tion does require permission.We appreciate, but do not require, attribution. An attribution usually includes thetitle, authors, publisher, and ISBN. For example: “Learning Perl, 7th edition, by Ran‐dal Schwartz, brian foy, and Tom Phoenix (O’Reilly). Copyright 2017 RandalSchwartz, brian foy, and Tom Phoenix, 978-1-491-95432-4.” If you feel your use ofcode examples falls outside fair use or the permission given above, feel free to contactus at permissions@oreilly.com.O’Reilly SafariSafari (formerly Safari Books Online) is a membership-basedtraining and reference platform for enterprise, government,educators, and individuals.Members have access to thousands of books, training videos, Learning Paths, interac‐tive tutorials, and curated playlists from over 250 publishers, including O’ReillyMedia, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press,John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, AdobePress, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, andCourse Technology, among others.For more information, please visit http://oreilly.com/safari.How to Contact UsWe have tested and verified all the information in this book to the best of our abili‐ties, but you may find that features have changed or that we have inadvertently leterrors slip through the production of the book. Please let us know of any errors thatyou find, as well as suggestions for future editions, by writing to:O’Reilly Media, Inc.1005 Gravenstein Highway NorthSebastopol, CA 954721-800-998-9938 (in the U.S. or Canada)Preface xiii

1-707-829-7000 (international/local)1-707-829-0104 (fax)We have a web page for the book, where we’ll list examples, errata, and any additionalinformation. It also offers a downloadable set of text files (and a couple of Perl pro‐grams) that are useful, but not required, when doing some of the exercises. You canaccess this page at http://www.learning-perl.com or go to the O’Reilly page.To comment or ask technical questions about this book, send email toinfo@oreilly.com.For more information about our books, courses, conferences, and news, see our web‐site at http://www.oreilly.com.Find us on Facebook: http://facebook.com/oreillyFollow us on Twitter: http://twitter.com/oreillymediaWatch us on YouTube: http://www.youtube.com/oreillymediaHistory of This BookFor the curious, here’s how Randal tells the story of how this book came about:After I had finished the first Programming perl book with Larry Wall (in 1991), I wasapproached by Taos Mountain Software in Silicon Valley to produce a trainingcourse. This included having me deliver the first dozen or so courses and train theirstaff to continue offering the course. I wrote the course for them1 and delivered it forthem as promised.On the third or fourth delivery of that course (in late 1991), someone came up to meand said, “You know, I really like Programming perl, but the way the material is pre‐sented in this course is so much easier to follow—you oughta write a book like thiscourse.” It sounded like an opportunity to me, so I started thinking about it.I wrote to Tim O’Reilly with a proposal based on an outline that was similar to thecourse I was presenting for Taos—although I had rearranged and modified a few ofthe chapters based on observations in the classroom. I think that was my fastest pro‐posal acceptance in history—I got a message from Tim within 15 minutes, saying“We’ve been waiting for you to pitch a second book—Programming perl is selling likegangbusters.” That started the effort over the next 18 months to finish the first editionof Learning Perl.1 In the contract, I retained the rights to the exercises, hoping someday to reuse them in some other way, like inthe magazine columns I was writing at the time. The exercises are the only things that leapt from the Taoscourse to the book.xiv Preface

During that time, I was starting to see an opportunity to teach Perl classes outsideSilicon Valley,2 so I created a class based on the text I was writing for Learning Perl. Igave a dozen classes for various clients (including my primary contractor, Intel Ore‐gon), and used the feedback to fine-tune the book draft even further.The first edition hit the streets on the first day of November 1993,3 and became asmashing success, frequently even outpacing Programming perl book sales.The back-cover jacket of the first book said “written by a leading Perl trainer.” Well,that became a self-fulfilling prophecy. Within a few months, I was starting to getemail from all over the United States asking me to teach at their site. In the followingseven years, my company became the leading worldwide on-site Perl training com‐pany, and I had personally racked up (literally) a million frequent-flier miles. It didn’thurt that the Web started taking off about then, and the webmasters and webmis‐tresses picked Perl as the language of choice for content management, interactionthrough CGI, and maintenance.For two years, I worked closely with Tom Phoenix in his role as lead trainer and con‐tent manager for Stonehenge, giving him charter to experiment with the “Llama”course by moving things around and breaking things up. When we had come up withwhat we thought was the best major revision of the course, I contacted O’Reilly andsaid, “It’s time for a new book!” And that became the third edition.Two years after writing the third edition of the Llama, Tom and I decided it was timeto push our follow-on “advanced” course out into the world as a book, for peoplewriting programs that are “100 to 10,000 lines of code.” And together we created thefirst Alpaca book (Learning Perl Objects, References, and Modules), released in 2003.But fellow instructor brian d foy had noticed that we could use some rewriting inboth books, because our courseware still needed to track the changing needs of thetypical student. So, he pitched the idea to O’Reilly to take on rewriting both the Llamaand the Alpaca. This edition of the Llama reflects those changes. brian has really beenthe lead writer here, working with my occasional guidance, and has done a brilliantjob of the usual “herding cats” that a multiple-writer team generally feels like.On December 18, 2007, the Perl 5 Porters released Perl 5.10, a significant new versionof Perl with several new features. The previous version, 5.8, had focused on theunderpinnings of Perl and its Unicode support. The latest version, starting from thestable 5.8 foundation, was able to add completely new features, some of which it bor‐rowed from the development of Perl 6. Some of these features, such as named cap‐2 My Taos contract had a non-compete clause, so I had to stay out of Silicon Valley with any similar courses,which I respected for many years.3 I remember that date very well, because it was also the day I was arrested at my home for computer-relatedactivities around my Intel contract, a series of felony charges for which I was later convicted.Preface xv

tures in regular expressions, are much better than the old ways of doing things, thusperfect for Perl beginners. We hadn’t thought about a fifth edition of this book, butPerl 5.10 was so much better that we couldn’t resist.Since then, Perl has been under constant improvement and is keeping a regularrelease cycle. Each new Perl release has brought exciting new features, many of whichprogrammers have wanted for years. As long as Perl keeps doing that, we’ll keepupdating this book.Changes from the Previous EditionThe text is updated for the latest version, Perl 5.24, and some of the code only workswith that version. We note in the text when we are writing about a Perl 5.24 feature,and we mark those code sections with a special use statement that ensures you’reusing the right version:use v5.24; # this script requires Perl 5.24 or greaterIf you don’t see that use v5.24 in a code example (or a similar statement with a dif‐ferent version), it should work all the way back to Perl 5.8. To see which version ofPerl you have, try the -v command-line switch: perl -vIn some examples, we’ll show a lower minimum Perl version because that’s all theprogram needs. For instance, say was introduced in Perl v5.10:use v5.10;say "Howdy, Fred!";In most cases, we’ll probably forgo a new feature to make the examples work on asmany versions of Perl as possible. That doesn’t mean you shouldn’t use the new fea‐tures or that we don’t endorse them. We simply have a wide audience for this book.We include Unicode examples and features where appropriate. If you haven’t startedplaying with Unicode, you may want to read our primer in Appendix C. You have tobite the bullet sometime, so it might as well be now. You’ll see Unicode throughoutthe book, most notably in the chapters on scalars (Chapter 2), input/output (Chap‐ter 5), and sorting (Chapter 14).xvi Preface

Here’s a quick summary of the updated or new things in this edition: An appendix on experimental features (Appendix D) More Windows examples where appropriate Hexadecimal floating-point literals (v5.22) in Chapter 2 The experimental but very exciting subroutine signatures (v5.20) in Chapter 4 The more-secure double diamond line input operator (v5.22) in Chapter 5 Many updates to regular expressions and match operator flags in Chapters 7through 9 Use Time::Moment over DateTime as an example in Chapter 11 The experimental bitwise string operators in Chapter 12 Key-value slices (v5.20) in Chapter 16AcknowledgmentsFrom RandalI want to thank the Stonehenge trainers past and present (Joseph Hall, Tom Phoenix,Chip Salzenberg, brian d foy, and Tad McClellan) for their willingness to go out andteach in front of classrooms week after week and to come back with their notes aboutwhat’s working (and what’s not), so we could fine-tune the material for this book. Iespecially want to single out my coauthor and business associate, Tom Phoenix, forhaving spent many, many hours working to improve Stonehenge’s Llama course andto provide the wonderful core text for most of this book. And brian d foy for beingthe lead writer beginning with the fourth edition, and taking that eternal to-do itemout of my inbox so that it would finally happen.I also want to thank everyone at O’Reilly, especially our very patient editor and over‐seer for previous editions, Allison Randal (no relation, but she has a nicely spelled lastname), current editor Simon St. Laurent, and Tim O’Reilly himself for taking achance on me in the first place with the Camel and Llama books.I am also absolutely indebted to the thousands of people who have purchased the pasteditions of the Llama so that I could use the money to stay “off the streets and out ofjail,” and to those students in my classrooms who have trained me to be a bettertrainer, and to the stunning array of Fortune 1000 clients who have purchased ourclasses in the past and will continue to do so into the future.As always, a special thanks to Lyle and Jack, for teaching me nearly everything I knowabout writing. I won’t ever forget you guys.Preface xvii

From brianI have to thank Randal first, since I learned Perl from the first edition of this book,and then had to learn it again when he asked me to start teaching for Stonehenge in1998. Teaching is often the best way to learn. Since then, Randal has mentored me notonly in Perl but several other things he thought I needed to learn—like the time hedecided that we could use Smalltalk instead of Perl for a demonstration at a web con‐ference. I’m always amazed at the breadth of his knowledge. He’s the one who told meto start writing about Perl. Now I’m helping out on the book where I started. I’m hon‐ored, Randal.I probably only actually saw Tom Phoenix for less than two weeks in the entire time Iworked for Stonehenge, but I had been teaching his version of Stonehenge’s LearningPerl course for years. That version turned into the third edition of this book. Byteaching Tom’s new version, I found new ways to explain almost everything, andlearned even more corners of Perl.When I convinced Randal that I should help out on the Llama update, I was anointedas the maker of the proposal to the publisher, the keeper of the outline, and the ver‐sion control wrangler. Our editor, Allison Randal, helped me get all of those set upand endured my frequent emails without complaining. After Allison went on to otherthings, Simon St. Laurent has been extremely helpful in the role of editor and insideguy at O’Reilly, patiently waiting for the right phase of the moon to suggest anotherupdate.From TomI’ve got to echo Randal’s thanks to everyone at O’Reilly. For the third edition of thisbook, Linda Mui was our editor, and I still thank her, for her patience in pointing outwhich jokes and footnotes were most excessive, while pointing out that she is in noway to blame for the ones that remain. Both she and Randal have guided me throughthe process of writing, and I am grateful. In a previous edition, Allison Randal tookcharge; now Simon St. Laurent has become the editor. My thanks go to each of themin recognition of their unique contributions.And another echo with regard to Randal and the other Stonehenge trainers, whohardly ever complained when I unexpectedly updated the course materials to try outa new teaching technique. You folks have contributed many different viewpoints onteaching methods that I would never have seen.For many years, I worked at the Oregon Museum of Science and Industry (OMSI),and I’d like to thank the folks there for letting me hone my teaching skills as I learnedto build a joke or two into ev

Learning Perl Making Easy Things Easy and Hard Things Possible SEVENTH EDITION Beijing Boston Farnham Sebastopol Tokyo. 978-1-491-95432-4 [LSI] Learning Perl by Randal L. Schwartz, brian d foy, and Tom Phoenix . Welcome to the seventh edition of Learning Perl, updated for Perl 5.24 and its latest features. This book is still mostly good even .