8 t C h o v E ers Pditi e o rl n Learning 5. 3 4 Perl Making Easy Things Easy and Hard Things Possible Randal L. Schwartz, brian d foy & Tom Phoenix Praise for Learning Perl Still the best way to learn Perl: friendly, accurate, and encouraging. —Nathan Torkington, Coauthor of the Perl Cookbook I consider the Llama the de facto standard when it comes to an introductory book for the Perl language. It’s coherent, easy to approach, and it broadly covers the language from legacy information to the bleeding edge. —Grzegorz Szpetkowski, Software Engineer, Intel Technology Poland Learning Perl is an investment that will help unlock the full potential of this powerful programming language. The authors are insightful as they methodically tackle a maze of new and exciting concepts that should be part of everyone’s journey towards Perl proficiency. —André Philipp, Freelance software engineer Learning Perl [4th ed.] should rightly be regarded as one of the classic texts for Perl programmers to read through at least once in their Perl careers. The book is chock-full of useful information, and even experienced Perl coders would do well to at least leaf through the pages of this book for paradigms to help their coding. —Craig Maloney, Slashdot reviewer EIGHTH EDITION Learning Perl Making Easy Things Easy and Hard Things Possible Randal L. Schwartz, brian d foy, and Tom Phoenix BBeeiijjiinngg BBoossttoonn FFaarrnnhhaamm SSeebbaassttooppooll TTookkyyoo Learning Perl by Randal L. Schwartz, brian d foy, and Tom Phoenix Copyright © 2021 Enhydra Services, LLC. 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://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Acquisitions Editor: Suzanne McQuade Indexer: WordCo Indexing Services, Inc. Development Editor: Jill Leonard Interior Designer: David Futato Production Editor: Daniel Elfanbaum Cover Designer: Karen Montgomery Copyeditor: Audrey Doyle Illustrator: Kate Dullea Proofreader: Kim Cofer July 2021: Eighth Edition Revision History for the Eighth Edition 2021-06-29: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492094951 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Perl, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the authors, and do not represent the publisher’s views. While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-492-09495-1 [GP] Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Questions and Answers 1 Is This the Right Book for You? 1 What About the Exercises and Their Answers? 2 What If I’m a Perl Course Instructor? 3 What Does “Perl” Stand For? 4 Why Did Larry Create Perl? 4 Why Didn’t Larry Just Use Some Other Language? 4 Is Perl Easy or Hard? 5 How Did Perl Get to Be So Popular? 6 What’s Happening with Perl Now? 7 What’s Perl Really Good For? 7 What Is Perl Not Good For? 8 How Can I Get Perl? 8 What Is CPAN? 9 Is There Any Kind of Support? 9 What If I Find a Bug in Perl? 10 How Do I Make a Perl Program? 10 A Simple Program 11 What’s Inside That Program? 13 How Do I Compile My Perl Program? 15 A Whirlwind Tour of Perl 15 Exercises 17 v 2. Scalar Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Numbers 19 All Numbers Have the Same Format Internally 20 Integer Literals 20 Nondecimal Integer Literals 20 Floating-Point Literals 21 Numeric Operators 22 Strings 23 Single-Quoted String Literals 23 Double-Quoted String Literals 24 String Operators 25 Automatic Conversion Between Numbers and Strings 26 Perl’s Built-in Warnings 27 Interpreting Nondecimal Numerals 28 Scalar Variables 29 Choosing Good Variable Names 30 Scalar Assignment 31 Compound Assignment Operators 31 Output with print 32 Interpolation of Scalar Variables into Strings 32 Creating Characters by Code Point 34 Operator Precedence and Associativity 34 Comparison Operators 36 The if Control Structure 37 Boolean Values 37 Getting User Input 38 The chomp Operator 39 The while Control Structure 40 The undef Value 40 The defined Function 41 Exercises 42 3. Lists and Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Accessing Elements of an Array 44 Special Array Indices 45 List Literals 45 The qw Shortcut 46 List Assignment 47 The pop and push Operators 49 The shift and unshift Operators 49 The splice Operator 50 vi | Table of Contents Interpolating Arrays into Strings 51 The foreach Control Structure 52 Perl’s Favorite Default: $_ 53 The reverse Operator 53 The sort Operator 54 The each Operator 54 Scalar and List Context 55 Using List-Producing Expressions in Scalar Context 56 Using Scalar-Producing Expressions in List Context 57 Forcing Scalar Context 58 <STDIN> in List Context 58 Exercises 59 4. Subroutines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Defining a Subroutine 61 Invoking a Subroutine 62 Return Values 62 Arguments 64 Private Variables in Subroutines 66 Variable-Length Parameter Lists 67 A Better &max Routine 67 Empty Parameter Lists 68 Notes on Lexical (my) Variables 69 The use strict Pragma 70 The return Operator 71 Omitting the Ampersand 72 Nonscalar Return Values 74 Persistent, Private Variables 74 Subroutine Signatures 76 Prototypes 78 Exercises 79 5. Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 Input from Standard Input 81 Input from the Diamond Operator 83 The Double Diamond 85 The Invocation Arguments 85 Output to Standard Output 86 Formatted Output with printf 89 Arrays and printf 91 Filehandles 91 Table of Contents | vii Opening a Filehandle 93 Binmoding Filehandles 96 Bad Filehandles 96 Closing a Filehandle 97 Fatal Errors with die 97 Warning Messages with warn 99 Automatically die-ing 99 Using Filehandles 100 Changing the Default Output Filehandle 100 Reopening a Standard Filehandle 101 Output with say 101 Filehandles in a Scalar 102 Exercises 104 6. Hashes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 What Is a Hash? 105 Why Use a Hash? 107 Hash Element Access 108 The Hash as a Whole 109 Hash Assignment 110 The Big Arrow 111 Hash Functions 112 The keys and values Functions 112 The each Function 113 Typical Use of a Hash 115 The exists Function 115 The delete Function 115 Hash Element Interpolation 116 The %ENV Hash 116 Exercises 117 7. Regular Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Sequences 119 Practice Some Patterns 121 The Wildcard 123 Quantifiers 125 Grouping in Patterns 129 Alternation 132 Character Classes 134 Character Class Shortcuts 135 Negating the Shortcuts 136 viii | Table of Contents