Learning Perl 6.Pdf
Total Page:16
File Type:pdf, Size:1020Kb
Learning Perl 6 KEEPING THE EASY, HARD, AND IMPOSSIBLE WITHIN REACH brian d foy www.allitebooks.com www.allitebooks.com Learning Perl 6 Keeping the Easy, Hard, and Impossible Within Reach brian d foy Beijing Boston Farnham Sebastopol Tokyo www.allitebooks.com Learning Perl 6 by brian d foy Copyright © 2018 brian d foy. 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: Jeff Bleiel Indexer: Lucie Haskins Production Editor: Nicholas Adams Interior Designer: David Futato Copyeditor: Rachel Head Cover Designer: Karen Montgomery Proofreader: Kim Cofer Illustrator: Rebecca Demarest September 2018: First Edition Revision History for the First Edition 2018-08-24: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781491977682 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning Perl 6, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author 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-97768-2 [LSI] www.allitebooks.com Table of Contents Preface. xiii 1. Introduction. 1 Why Perl 6? 1 First Steps with the REPL 2 Reading the Documentation 4 Basic Syntax 4 Terms 5 Operators and Expressions 5 Statements 8 Blocks 8 Comments 9 Unspace 10 Objects and Classes 10 Variables 11 Simple Output 13 Lexical Scope 13 Predefined Variables 14 Making and Running a Program 15 Summary 16 2. Number Guessing. 17 Binding and Assignment 17 A MAIN Program 18 Program Arguments 19 Prompting for Values 21 Literal Numbers 22 Formatting Numbers 23 iii www.allitebooks.com Numeric Operations 24 Conditional Execution 27 Boolean Values 27 Comparing Things 30 Conditional Branching 33 Putting It All Together 35 Summary 37 3. Numbers. 39 Number Types 39 Integers 40 Type Constraints 40 Smart Matching 42 Rational Numbers 44 Imaginary and Complex Numbers 46 Numbers Small and Large 48 The Numeric Hierarchy 49 Summary 50 4. Strings. 51 Literal Quoting 51 Escaped Strings 52 Adverbs for Quoting 53 String Operators and Methods 54 Looking Inside Strings 56 Normal Form Grapheme 57 String Comparisons 58 Prompting for Input 59 Number to String Conversions 61 String to Number Conversions 61 Interpolated Strings 63 Here Docs 66 Shell Strings 67 Shell Safety 68 Fancier Quoting 69 Summary 70 5. Building Blocks. 71 Blocks 71 Lexical Scope 72 Control Structures 73 Phasers 75 iv | Table of Contents Storing Blocks 78 Blocks with Parameters 79 Simple Subroutines 82 Named Subroutines 84 Whatever Code 85 Subsets 85 Summary 87 6. Positionals. 89 Constructing a List 89 Iterating All the Elements 92 Ranges 96 The @ Coercer 97 Sequences 98 Infinite Lazy Lists 100 Gathering Values 102 Single-Element Access 103 Changing a Single Element 105 Multiple-Element Access 106 Arrays 106 Constructing an Array 107 Interpolating Arrays 108 Array Operations 109 Lists of Lists 110 Flattening Lists 111 Interesting Sublists 112 Combining Lists 113 The Zip Operator, Z 113 The Cross Operator, X 114 The Hyperoperators 115 The Reduction Operator 116 Filtering Lists 117 Transforming a List 118 Sorting Lists 119 Sorting on Multiple Comparisons 121 Summary 122 7. When Things Go Wrong. 123 Exceptions 123 Catching Exceptions 124 Backtraces 126 Rethrowing Errors 129 Table of Contents | v Throwing Your Own Exceptions 130 Defining Your Own Exception Types 131 Failures 131 Warnings 132 The Wisdom of Exceptions 133 Summary 134 8. Files and Directories, Input and Output. 135 File Paths 135 File Test Operators 137 File Metadata 139 Linking and Unlinking Files 140 Renaming and Copying Files 142 Manipulating Directories 143 Directory Listings 144 Creating Directories 145 Removing Directories 145 Formatted Output 146 Common Formatting Tasks 148 The Standard Filehandles 149 Standard Output 149 Standard Error 150 Standard Input 151 Reading Input 151 Reading Lines 152 Reading a File 153 Writing Output 154 Opening a File for Writing 154 Binary Files 155 Moving Around 156 Writing Binary Files 156 Summary 157 9. Associatives. 159 Pairs 159 Adverbs 160 Modifying a Pair 161 Maps 162 Checking Keys 163 Creating from a Positional 163 Checking Allowed Values 164 Hashes 165 vi | Table of Contents Accumulating with a Hash 167 Multilevel Hashes 169 Summary 170 10. Using Modules. 171 Installing Modules 171 Loading Modules 172 Finding the Module 173 Lexical Effect 175 Loading a Module at Runtime 176 Fetching Data from the Web 179 Running Perl 5 in Perl 6 179 Summary 180 11. Subroutines. 181 A Basic Subroutine 181 Extra Arguments 182 Explicit Returns 182 Recursing 184 Iterating Instead of Recursing 184 Storing Subroutines in Libraries 185 Exporting Subroutines 186 Positional Parameters 187 Slurpy Parameters 188 Have It Both Ways 189 Combining Slurpies 190 Optional and Default Arguments 191 Parameter Traits 191 Parameter Constraints 192 Same Name, Different Signature 193 Literal Value Parameters 193 Number of Arguments 195 Parameter Types 195 Named Parameters 197 Required Named Parameters 198 Named Parameters for Free 198 Mixed Parameters 199 Return Types 199 Summary 201 12. Classes. 203 Your First Class 203 Table of Contents | vii Defining Methods 204 Private Methods 205 Defining Subroutines 206 Objects 206 Private Attributes 207 Public Attributes 209 multi Methods 210 Inheriting Types 212 Checking Inheritance 214 Stub Methods 214 Controlling Object Creation 215 Building Objects 216 Tweaking Objects 219 Private Classes 220 Summary 221 13. Roles. 223 Adding Behavior to Classes 223 Applying Multiple Roles 224 Methods in Roles 225 De-Conflicting Roles 226 Anonymous Roles 229 Summary 231 14. Junctions and Sets. 233 Junctions 233 any 233 all 237 one 237 none 238 Some Junctive Tricks 238 Sets 239 Set Operations 242 Summary 243 15. Regular Expressions. 245 The Match Operator 245 Match Operator Syntax 246 Successful Matches 247 Defining a Pattern 248 Predefined Patterns 249 Matching Nonliteral Characters 250 viii | Table of Contents Matching Any Character 251 Matching Types of Characters 253 User-Defined Character Classes 255 Matching Adverbs 257 Matching Either Case 257 Ignoring Marks 259 Global Matches 259 Things That Use Patterns 260 Substitutions 260 Summary 261 16. Fancier Regular Expressions. 263 Quantifiers 263 Zero or More 264 Greediness 265 Zero or One 265 Minimal and Maximal 266 Controlling Quantifiers 267 Turning Off Backtracking 267 Captures 268 Named Captures 269 A Capture Tree 271 Backreferences 272 Surrounders and Separators 273 Assertions 274 Anchors 275 Conditions 276 Code Assertions 277 Alternations 279 First Match 279 Longest Token Matching 281 Summary 283 17. Grammars. 285 A Simple Grammar 285 Multiple Rules 288 Debugging Grammars 290 Grammar::Tracer 290 Grammar::Debugger 291 A Simple Action Class 291 Creating an Abstract Syntax Tree 292 Ratcheting 294 Table of Contents | ix Parsing JSON 295 Parsing CSV 298 Adjusting the Grammar 300 Using Roles in Grammars 301 Summary 302 18. Supplies, Channels, and Promises. 303 Supplies 303 Multiple Taps 305 Live Supplies 306 Channels 307 Promises 309 Waiting for Promises 310 Waiting for Multiple Promises 311 Managing Your Own Promises 312 Promise Junctions 314 Reactive Programming 315 Reacting in the Background 318 Summary 320 19. Controlling Other Programs. 321 Quick and Easy 321 Quoted Commands 322 Safer Commands 323 Writing to a Proc 324 Procs 325 Asynchronous Control 326 Summary 327 20. Advanced Topics. 329 One-Liners 329 Declarator Block Comments 329 Feed Operators 330 Destructuring Signatures 331 Defining Your Own Operators 331 Perl 5 Patterns 332 Shaped Arrays 332 Typed Containers 332 NativeCall 333 The with Topicalizer 333 21. Conclusion. 335 x | Table of Contents Glossary. 337 A. Exercise Answers. 349 Index. 435 Table of Contents | xi Preface Welcome to the first edition of Learning Perl 6, a book title that sounds similar to oth‐ ers you may have read and I may have written. This one, however, is my first book about the language called “Perl 6.” I know the name is a bit confusing; I’m not in charge of that part. I’m just the book writer. Okay, I can see you’re not satisfied with that. Here’s the short answer you probably want: if you need to learn Perl because someone made that choice for you, you’re probably looking for my other book, Learning Perl, that covers the widely used Perl 5. That’s the stable ol’ workhorse that’s been around virtually forever. This one is about the new language that’s still growing up and isn’t in wide use yet. Here’s the longer answer for those of you who are still reading. You either know that you want Perl 6 or you don’t really care which one you get as long as you learn a new language. The Backstory of Perl 6 At the Perl Conference in 2000, a group of Perl people got together in a hotel confer‐ ence room in Monterey, California.