Learning Perl MAKING EASY THINGS EASY and HARD THINGS POSSIBLE
Total Page:16
File Type:pdf, Size:1020Kb
7th Edition Learning Perl MAKING EASY THINGS EASY AND HARD THINGS POSSIBLE Randal L. Schwartz, brian d foy & Tom Phoenix SEVENTH EDITION Learning Perl Making Easy Things Easy and Hard Things Possible Randal L. Schwartz, brian d foy, and Tom Phoenix Beijing Boston Farnham Sebastopol Tokyo Learning Perl by Randal L. Schwartz, brian d foy, and Tom Phoenix Copyright © 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 are also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐ tutional sales department: 800-998-9938 or [email protected]. Editor: Heather Scherer Indexer: Lucie Haskins Production Editor: Melanie Yarbrough Interior Designer: David Futato Copyeditor: Jasmine Kwityn Cover Designer: Karen Montgomery Proofreader: Sonia Saruba Illustrator: Rebecca Demarest October 2016: Seventh Edition Revision History for the Seventh Edition 2016-10-05: First Release 2018-03-02: Second Release See 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, and related 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 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-491-95432-4 [LSI] Table of Contents Preface. xi 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? 7 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 16 Exercises 17 2. Scalar Data. 19 Numbers 19 iii All Numbers Have the Same Format Internally 20 Integer Literals 20 Nondecimal Integer Literals 21 Floating-Point Literals 21 Numeric Operators 22 Strings 23 Single-Quoted String Literals 24 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 33 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 41 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 Interpolating Arrays into Strings 51 The foreach Control Structure 52 Perl’s Favorite Default: $_ 53 iv | Table of Contents 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 58 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 Exercises 78 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 Opening a Filehandle 93 Binmoding Filehandles 96 Bad Filehandles 96 Closing a Filehandle 97 Fatal Errors with die 97 Table of Contents | v 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 102 Filehandles in a Scalar 102 Exercises 104 6. Hashes. 107 What Is a Hash? 107 Why Use a Hash? 109 Hash Element Access 110 The Hash as a Whole 111 Hash Assignment 112 The Big Arrow 113 Hash Functions 114 The keys and values Functions 114 The each Function 115 Typical Use of a Hash 116 The exists Function 117 The delete Function 117 Hash Element Interpolation 118 The %ENV hash 118 Exercises 119 7. Regular Expressions. 121 Sequences 121 Practice Some Patterns 123 The Wildcard 125 Quantifiers 126 Grouping in Patterns 130 Alternation 133 Character Classes 134 Character Class Shortcuts 135 Negating the Shortcuts 137 Unicode Properties 137 Anchors 138 Word Anchors 139 Exercises 141 vi | Table of Contents 8. Matching with Regular Expressions. 143 Matches with m// 143 Match Modifiers 144 Case-Insensitive Matching with /i 144 Matching Any Character with /s 144 Adding Whitespace with /x 145 Combining Option Modifiers 146 Choosing a Character Interpretation 146 Beginning and End-of-Line Anchors 148 Other Options 149 The Binding Operator =~ 149 The Match Variables 150 The Persistence of Captures 151 Noncapturing Parentheses 152 Named Captures 153 The Automatic Match Variables 155 Precedence 157 Examples of Precedence 158 And There’s More 158 A Pattern Test Program 159 Exercises 159 9. Processing Text with Regular Expressions. 161 Substitutions with s/// 161 Global Replacements with /g 162 Different Delimiters 163 Substitution Modifiers 163 The Binding Operator 163 Nondestructive Substitutions 163 Case Shifting 164 Metaquoting 166 The split Operator 166 The join Function 168 m// in List Context 168 More Powerful Regular Expressions 169 Nongreedy Quantifiers 169 Fancier Word Boundaries 170 Matching Multiple-Line Text 172 Updating Many Files 172 In-Place Editing from the Command Line 174 Exercises 176 Table of Contents | vii 10. More Control Structures. 177 The unless Control Structure 177 The else Clause with unless 178 The until Control Structure 178 Statement Modifiers 179 The Naked Block Control Structure 180 The elsif Clause 181 Autoincrement and Autodecrement 182 The Value of Autoincrement 182 The for Control Structure 183 The Secret Connection Between foreach and for 185 Loop Controls 186 The last Operator 186 The next Operator 187 The redo Operator 188 Labeled Blocks 189 The Conditional Operator 190 Logical Operators 191 The Value of a Short-Circuit Operator 192 The defined-or Operator 193 Control Structures Using Partial-Evaluation Operators 194 Exercises 196 11. Perl Modules. 197 Finding Modules 197 Installing Modules 198 Using Your Own Directories 199 Using Simple Modules 201 The File::Basename Module 202 Using Only Some Functions from a Module 203 The File::Spec Module 204 Path::Class 205 Databases and DBI 205 Dates and Times 206 Exercises 207 12. File Tests. 209 File Test Operators 209 Testing Several Attributes of the Same File 213 Stacked File Test Operators 214 The stat and lstat Functions 216 The localtime Function 217 viii | Table of Contents Bitwise Operators 218 Using Bitstrings 219 Exercises 222 13. Directory Operations. 223 The Current Working Directory 223 Changing the Directory 224 Globbing 225 An Alternate Syntax for Globbing 227 Directory Handles 228 Manipulating Files and Directories 229 Removing Files 230 Renaming Files 231 Links and Files 232 Making and Removing Directories 237 Modifying Permissions 239 Changing Ownership 239 Changing Timestamps 240 Exercises 240 14. Strings and Sorting. 243 Finding a Substring with index 243 Manipulating a Substring with substr 245 Formatting Data with sprintf 246 Using sprintf with “Money Numbers” 247 Advanced Sorting 248 Sorting a Hash by Value 252 Sorting by Multiple Keys 253 Exercises 254 15. Process Management. 255 The system Function 255 Avoiding the Shell 258 The Environment Variables 260 The exec Function 261 Using Backquotes to Capture Output 262 Using Backquotes in a List Context 264 External Processes with IPC::System::Simple 266 Processes as Filehandles 267 Getting Down and Dirty with Fork 269 Sending and Receiving Signals 270 Exercises 273 Table of Contents | ix 16. Some Advanced Perl Techniques. 275 Slices 275 Array Slice 277 Hash Slice 279 Key-Value Slices 280 Trapping Errors 281 Using eval 281 More Advanced Error Handling 285 Picking Items from a List with grep 287 Transforming Items from a List with map 288 Fancier List Utilities 289 Exercises 291 A. Exercise Answers. 293 B. Beyond the Llama. 329 C. A Unicode Primer. 339 D.