Perl 6 Fundamentals - Anarcho-Copy

1y ago
5 Views
2 Downloads
2.58 MB
151 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Javier Atchley
Transcription

Perl 6FundamentalsA Primer with Examples, Projects,and Case Studies—Moritz LenzForeword by Larry Wall, creator of Perl

Perl 6 FundamentalsA Primer with Examples,Projects, and Case StudiesMoritz LenzForeword by Larry Wall, creator of Perl

Perl 6 Fundamentals: A Primer with Examples, Projects, and Case StudiesMoritz LenzFürth, Bayern, GermanyISBN-13 (pbk): 978-1-4842-2898-2DOI 10.1007/978-1-4842-2899-9ISBN-13 (electronic): 978-1-4842-2899-9Library of Congress Control Number: 2017948406Copyright 2017 by Moritz LenzThis work is subject to copyright. All rights are reserved by the Publisher, whether thewhole or part of the material is concerned, specifically the rights of translation, reprinting,reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in anyother physical way, and transmission or information storage and retrieval, electronicadaptation, computer software, or by similar or dissimilar methodology now known orhereafter developed.Trademarked names, logos, and images may appear in this book. Rather than use atrademark symbol with every occurrence of a trademarked name, logo, or image we use thenames, logos, and images only in an editorial fashion and to the benefit of the trademarkowner, with no intention of infringement of the trademark.The use in this publication of trade names, trademarks, service marks, and similar terms,even if they are not identified as such, is not to be taken as an expression of opinion as towhether or not they are subject to proprietary rights.While the advice and information in this book are believed to be true and accurate at thedate of publication, neither the authors nor the editors nor the publisher can accept anylegal responsibility for any errors or omissions that may be made. The publisher makesno warranty, express or implied, with respect to the material contained herein.Cover image by Freepik (www.freepik.com)Managing Director: Welmoed SpahrEditorial Director: Todd GreenAcquisitions Editor: Steve AnglinDevelopment Editor: Matthew MoodieTechnical Reviewer: Massimo NardoneCoordinating Editor: Mark PowersCopy Editor: Brendan FrostDistributed to the book trade worldwide by Springer Science Business Media New York,233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media,LLC is a California LLC and the sole member (owner) is Springer Science Business MediaFinance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.For information on translations, please e-mail rights@apress.com, or ss titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference ourPrint and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.Any source code or other supplementary material referenced by the author in this book isavailable to readers on GitHub via the book’s product page, located at www.apress.com/9781484228982. For more detailed information, please visit http://www.apress.com/source-code.Printed on acid-free paper

Contents at a GlanceAbout the Author xiAbout the Technical Reviewer xiiiAcknowledgments xvForeword xvii Chapter 1: What Is Perl 6? 1 Chapter 2: Running Rakudo Perl 6 5 Chapter 3: Formatting a Sudoku Puzzle 9 Chapter 4: Datetime Conversion for the Command Line 23 Chapter 5: Testing say( ) 39 Chapter 6: Silent-Cron, a Cron Wrapper 43 Chapter 7: Stateful Silent-Cron 61 Chapter 8: Review of the Perl 6 Basics 67 Chapter 9: Parsing INI Files Using Regexes and Grammars 73 Chapter 10: A File and Directory Usage Graph 95 Chapter 11: A Unicode Search Tool 113 Chapter 12: Plotting Using Inline::Python and Matplotlib 119 Chapter 13: What’s Next? 135Index 139iii

ContentsAbout the Author xiAbout the Technical Reviewer xiiiAcknowledgments xvForeword xvii Chapter 1: What Is Perl 6? 11.1  Perl 5, the Older Sister 11.2  Library Availability 21.3  Why Should I Use Perl 6? 21.4  Summary 3 Chapter 2: Running Rakudo Perl 6 52.1  Installers 52.2  Docker 62.3  Building from Source 72.4  Testing Your Rakudo Star Installation 82.5  Documentation 82.6  Summary 8 Chapter 3: Formatting a Sudoku Puzzle 93.1  Making the Sudoku Playable 123.2  Shortcuts, Constants, and More Shortcuts 16v

Contents3.3  I/O and Other Tragedies 183.4  Get Creative! 203.5  Summary 21 Chapter 4: Datetime Conversion for the Command Line 234.1  Libraries to the Rescue 234.2  DateTime Formatting 264.3  Looking the Other Way 284.4  Dealing with Time 304.5  Tighten Your Seat Belt 314.6  MAIN Magic 334.7  Automated Tests 344.8  Summary 38 Chapter 5: Testing say( ) 395.1  Summary 42 Chapter 6: Silent-Cron, a Cron Wrapper 436.1  Running Commands Asynchronously 436.2  Implementing Timeouts 466.3  More on Promises 486.4  Possible Extensions 516.5  Refactoring and Automated Tests 516.5.1  Refactoring 516.5.2  Mocking and Testing 536.5.3  Improving Reliability and Timing 586.5.4  Installing a Module 586.6  Summary 59vi

Contents Chapter 7: Stateful Silent-Cron 617.1  Persistent Storage 617.2  Developing the Storage Back End 627.3  Using the Storage Back End 657.4  Room for Expansion 667.5  Summary 66 Chapter 8: Review of the Perl 6 Basics 678.1  Variables and Scoping 678.2  Subroutines 678.3  Classes and Objects 698.4  Concurrency 718.5  Outlook 71 Chapter 9: Parsing INI Files Using Regexes and Grammars 739.1  Regex Basics 749.1.1  Character Classes 759.1.2  Quantifiers 759.1.3  Alternatives 769.2  Parsing the INI Primitives 769.3  Putting Things Together 799.4  Backtracking 809.5  Grammars 829.6  Extracting Data from the Match 839.7  Generating Good Error Messages 889.7.1  Failure Is Normal 889.7.2  Detecting Harmful Failure 899.7.3  Providing Context 909.7.4  Shortcuts for Parsing Matching Pairs 92vii

Contents9.8  Write Your Own Grammars 939.9  Summary 93 Chapter 10: A File and Directory Usage Graph 9510.1  Reading File Sizes 9510.2  Generating a Tree Map 9710.3  Flame Graphs 10110.4  Functional Refactorings 10310.5  More Language Support for Functional Programming 10910.6  More Improvements 11010.7  Explore! 11110.8  Summary 112 Chapter 11: A Unicode Search Tool 11311.1 Code Points, Grapheme Clusters, and Bytes 11511.2  Numbers 11611.3  Other Unicode Properties 11711.4  Collation 11711.5  Summary 118 Chapter 12: Plotting Using Inline::Python and Matplotlib 11912.1  Extracting the Stats 11912.2  Plotting with Python 12012.3  Bridging the Gap 12212.4  Using the Bridge to Plot 12312.5  Stacked Plots 125viii

Contents12.6  Idiomatic Use of Inline::Python 12912.6.1  Types of Python APIs 12912.6.2  Mapping the Function API 13012.6.3  An Object-Oriented Interface 13212.7  Summary 134 Chapter 13: What’s Next? 13513.1  Scaling Your Code Base 13513.2  Packaging Your Application 13613.2.1  Packaging as a Traditional Perl 6 Module 13613.2.2  Deploying with Docker 13713.2.3  Windows Installers 13713.3  Closing Thoughts 137Index 139ix

About the AuthorMoritz Lenz is a software engineer and architect.In the Perl community, he is well known forhis contributions to the Perl 6 programminglanguage, the Rakudo Perl 6 compiler, related testsuite, infrastructure, and tools. At his employer,noris network AG, he introduced ContinuousDelivery for many in-house-developedapplications, and now wants to share hisexperience with the wider world.xi

About the TechnicalReviewerMassimo Nardone has more than 22 yearsof experiences in Security, Web/Mobiledevelopment, and Cloud and IT Architecture.His true IT passions are Security and Android.He has been programming and teaching howto program with Android, Perl, PHP, Java, VB,Python, C/C , and MySQL for more than 20 years.He holds a Master of Science degree inComputing Science from the University ofSalerno, Italy.He has worked as a Project Manager, SoftwareEngineer, Research Engineer, Chief SecurityArchitect, Information Security Manager, PCI/SCADA Auditor, and Senior Lead IT Security/Cloud/SCADA Architect for many years.Massimo’s technical skills include Security, Android, Cloud, Java, MySQL,Drupal, Cobol, Perl, Web and Mobile development, MongoDB, D3, Joomla,Couchbase, C/C , WebGL, Python, Pro Rails, Django CMS, Jekyll, and Scratch.He currently works as Chief Information Security Officer (CISO) forCargotec Oyj.He worked as visiting lecturer and supervisor for exercises at the NetworkingLaboratory of the Helsinki University of Technology (Aalto University). He holdsfour international patents (PKI, SIP, SAML, and Proxy areas).Massimo has reviewed more than 40 IT books for different publishingcompanies, and he is the coauthor of Pro Android Games (Apress, 2015).xiii

AcknowledgmentsThey say it takes a village to raise a child. Similar things can be said aboutwriting a book. It is only possible through the effort of many people, oftenunpaid volunteers who contribute just to see the project succeed, and out ofkindness of heart.I am very grateful for the review by and feedback from Paul Cochrane,Will Coleda, Elizabeth Mattijsen, Ryan Erwin, Claudio Ramirez, and MassimoNardone.Special thanks go to Larry Wall for creating Perl, for the great foreword, andfor shaping the community to be friendly, welcoming, and a second home to me.Finally, thanks go to my parents, for kindling my love both for books and forengineering. And most importantly to my family: to Signe, my wife, for constantsupport; and to my daughters Ida and Ronja for keeping me grounded in the realworld, and bringing joy to my life.xv

ForewordThe reason I’m writing this (and perhaps why you’re reading it), is that peoplejust give me way too much credit. Yeah, sure, I invented Perl 30 years ago, and Icoded the first five versions all by myself, pretty much. But for the last 20 years,the vast majority of the work has been done by other members of the industriousPerl community, who get far too little credit. To be sure, I don’t mind gettingextra credit: I’m human enough to enjoy the undue adulation, and I understandhow communities want—and possibly even need—to have a figurehead whorepresents the whole.I will gladly take credit, however, for the idea that a computer language musthave a vibrant community in order to thrive. From the beginning, that was theintent of Perl. It all comes down to linguistics: Perl was designed to work like anatural language on many levels, not just the syntactic level. In particular, everyliving language is symbiotic with the culture that conveys it forward into thefuture. More generally, natural languages are responsive to context on everylevel, and some of those levels are anthropological. People provide context toPerl, which in turn is designed to respond productively to that context.This may seem simple, but it’s a surprisingly tricky concept to bake intoa programming language and its culture. Just look at how many computerlanguages fail at it. In most programming cultures, you are a slave to thecomputer language. Rarely, if ever, do you get the feeling that the computerlanguage is there to work for you.We’re trying to change all that. So when the Perl community, back in 2000,decided to do a major redesign of Perl 5 to clean up the cruftier bits, we not onlywanted to fix things that we already knew were suboptimal, but we also wantedto do a better job of responding to cultural change, because we simply don’tknow what we’ll want in the future. So we thought about how best to futureproof a computer language; much of the current design is about maintainingcareful control of identity, mutability, dimensionality, typology, and extensibilityover time, so we could isolate changes to minimize collateral damage. Otherthan worrying about that, my main contribution as language designer was tounify the community’s contradictory desires into a coherent whole.All that being said, it’s still all about the community: nearly all theimplementation work was done by others, and most of the features that endedup in Perl 6 can be traced back through various revisions to the community’sxvii

Forewordoriginal RFCs. True, many of those original designs we deemed inadequate,but we never lost sight of the pain points those original suggestions were tryingto address. As a result, even though Perl 6 ended up to be quite a differentlanguage than Perl 5, it is still essentially Perl in spirit. We now think of Perl 6as the “younger sister” to Perl 5, and we expect the sisters will get along well inthe future. You’re allowed to be friends with either or both. They only squabbleoccasionally, as family do.Since 2000, we’ve had over 800 contributors to the Perl 6 effort, one way oranother. Some folks come and go, and that’s fine. We welcome the occasionalcontributor. On the other hand, we also honor those who strove greatly but paidthe price of burnout. And we deeply revere those who have already passed on,who contributed, in some cases, knowing they would never see the final result.But then there are those who have stuck with the Perl 6 effort throughthick and thin, through joy and frustration, who have patiently (or at leastpersistently!) risen to the challenge of building a better Perl community aroundthe revised Perl language, and who have gladly taken on the hard work of makingother people’s lives easy.One such is my friend Moritz Lenz, your author, and a much-respectedmember of our not-so-secret Perl 6 Cabal. Well, some days it’s more like the Perl6 Comedy Club.While thinking about this foreword, I guessed (and Moritz confirmed) thathe has a background in the performance arts. One can tell, because he seemsto have a natural feel for when to blend in as part of the ensemble, when to stepforward and take a solo lead, and when to step back again and let someone elsecome to the fore. In many ways, the Perl 6 effort has been like a jazz jam session,or like improv comedy, the kind of art where part of it is showing how cleverly welearn to work together and trade off roles on the fly.I’ve had to learn some of that myself. Good leaders don’t try to lead all thetime. That’s what bad leaders try to do. Often, a good leader is just “followingout in front,” sensing when the group behind wants a change of direction, andthen pretending to lead the group in that direction. Moritz knows how to dothat too.Hence, this book. It’s not just a reference, since you can always find suchmaterials online. Nor is it just a cookbook. I like to think of it as an extendedinvitation, from a well-liked and well-informed member of our circle, to peoplelike you who might want to join in on the fun. Because joy is what’s fundamentalto Perl. The essence of Perl is an invitation to love, and to be loved by, the Perlcommunity. It’s an invitation to be a participant of the gift economy, on both thereceiving and the giving end.xviii

ForewordSince Herr Doktor Professor Lenz is from Deutschland, I think it’sappropriate to end with one of my favorite German sayings:Liebe ist arm und reich,Fordert und gibt zugleich.Oder auf Englisch:Love is poor and rich,Taking and giving as one.Larry Wall, May 2017xix

CHAPTER 1What Is Perl 6?Perl 6 is a programming language. It is designed to be easily learned, read, andwritten by humans, and is inspired by natural language. It allows the beginnerto write in “baby Perl,” while giving the experienced programmer freedom ofexpression, from concise to poetic.Perl 6 is gradually typed. It mostly follows the paradigm of dynamicallytyped languages in that it accepts programs whose type safety it can’t guaranteeduring compilation. However, unlike many dynamic languages, it accepts andenforces type constraints. Where possible, the compiler uses type annotationsto make decisions at compile time that would otherwise only be possible atruntime.Many programming paradigms have influenced Perl 6. You can writeimperative, object-oriented, and functional programs in Perl 6. Declarativeprogramming is supported through features like multiple-dispatch, sub-typing,and the regex and grammar engine.Most lookups in Perl 6 are lexical, and the language avoids global state. Thismakes parallel and concurrent execution of programs easier, as does Perl 6’sfocus on high-level concurrency primitives. When you don’t want to be limitedto one CPU core, instead of thinking in terms of threads and locks, you tend tothink about promises and message queues.Perl 6 as a language is not opinionated about whether Perl 6 programs should becompiled or interpreted. Rakudo Perl 6—the main implementation—precompilesmodules on the fly and interprets scripts.1.1  Perl 5, the Older SisterAround the year 2000, Perl 5 development faced major strain from theconflicting desires to evolve and to keep backward compatibility.Perl 6 was the valve to release this tension. All the extension proposals thatrequired a break in backward compatibility were channeled into Perl 6, leaving itin a dreamlike state where everything was possible and nothing was fixed. It tookseveral years of hard work to get into a more solid state. Moritz Lenz 2017M. Lenz, Perl 6 Fundamentals, DOI 10.1007/978-1-4842-2899-9 11

Chapter 1 What Is Perl 6?During this time, Perl 5 also evolved, and the two languages are differentenough that most Perl 5 developers don’t consider Perl 6 a natural upgrade pathanymore, to the point that Perl 6 does not try to obsolete Perl 5 (at least not morethan it tries to obsolete any other programming language :-), and the first stablerelease of Perl 6 in 2015 does not indicate any lapse in support for Perl 5.Perl 5 is developed by a separate community of enthusiasts, who keep aneye on Perl 6 to find features worth adopting into Perl 5. So while the Perl 5 andPerl 6 communities have a certain overlap and communicate with each other,both thrive mostly independently.1.2  Library AvailabilityBeing a relatively young language, Perl 6 lacks the mature module ecosystemthat languages such as Perl 5 and Python provide.To bridge this gap, interfaces exist that allow you to call into librarieswritten in C, Python, Perl 5, and Ruby. The Perl 5 and Python interfaces aresophisticated enough that you can write a Perl 6 class that subclasses a classwritten in either language, and the other way around.So if you like a particular Python library, for example, you can simply load itinto your Perl 6 program through the Inline::Python module.1.3  Why Should I Use Perl 6?If you like the quick prototyping experience from dynamically typedprogramming languages, but you also want enough safety features to build big,reliable applications, Perl 6 is a good fit for you. Its gradual typing allows you towrite code without having a full picture of the types involved, and later introducetype constraints to guard against future misuse of your internal and external APIs.Perl has a long history of making text processing via regular expressions(regexes) very easy, but more complicated regexes have acquired a reputationof being hard to read and maintain. Perl 6 solves this by putting regexes on thesame level as code, allowing you to name them like subroutines, and even touse object-oriented features such as class inheritance and role composition tomanage code and regex reuse. The resulting grammars are very powerful andeasy to read. In fact, the Rakudo Perl 6 compiler parses Perl 6 source code with aPerl 6 grammar!Speaking of text, Perl 6 has amazing Unicode support. If you ask your userfor a number, and they enter it with digits that don’t happen to be the Arabicdigits from the ASCII range, Perl 6 still has you covered. And if you deal withgraphemes that cannot be expressed as a single Unicode code point, Perl 6 stillpresents it as a single character.2

Chapter 1 What Is Perl 6?There are more technical benefits that I could list, but more importantly,the language is designed to be fun to use. An important aspect of that is gooderror messages. Have you ever been annoyed at Python for typically giving justSyntaxError: invalid syntax when something’s wrong? This error couldcome from forgetting a closing parenthesis, for example. In this case, a Perl 6compiler saysUnable to parse expression in argument list; couldn't find final ')'which actually tells you what’s wrong. But this is just the tip of the iceberg. Thecompiler catches common mistakes and points out possible solutions, andeven suggests fixes for spelling mistakes. The Perl 6 community considers errormessages that are less than awesome, short LTA, to be worthy of bug reports, andmuch effort is spent into raising the bar for error messages.Finally, Perl 6 gives you the freedom to express your problem domain andsolution in different ways and with different programming paradigms. And ifthe options provided by the core language are not enough, it is designed withextensibility in mind, allowing you to introduce both new semantics forobject-oriented code and new syntax.1.4  SummaryPerl 6 is a flexible programming language that offers many cool and convenientfeatures to both beginners and experts. It offers flexibility, type checking, andpowerful Unicode and text processing support.3

CHAPTER 2Running Rakudo Perl 6Before we start exploring Perl 6, you should have an environment where youcan run Perl 6 code. So you need to install Rakudo Perl 6, currently the onlyactively developed Perl 6 compiler. Or even better, install Rakudo Star, which is adistribution that includes Rakudo itself, a few useful modules, and a tool that canhelp you install more modules.Installing Rakudo itself gives you just the compiler. It follows a monthlyrelease cycle, so it allows you to keep up to date with the latest developments.When you choose to install Rakudo Star, which is typical

In the Perl community, he is well known for his contributions to the Perl 6 programming language, the Rakudo Perl 6 compiler, related test suite, infrastructure, and tools. At his employer, noris network AG, he introduced Continuous Delivery for many in-house-developed applications, and now wants to share his experience with the wider world.

Related Documents:

Why Perl? Perl is built around regular expressions -REs are good for string processing -Therefore Perl is a good scripting language -Perl is especially popular for CGI scripts Perl makes full use of the power of UNIX Short Perl programs can be very short -"Perl is designed to make the easy jobs easy,

Perl can be embedded into web servers to speed up processing by as much as 2000%. Perl's mod_perl allows the Apache web server to embed a Perl interpreter. Perl's DBI package makes web-database integration easy. Perl is Interpreted Perl is an interpreted language, which means that your code can be run as is, without a

Other Perl resources from O’Reilly Related titles Learning Perl Programming Perl Advanced Perl Programming Perl Best Practices Perl Testing: A Developer’s . Intermedi

Run Perl Script Option 3: Create a Perl script my_script.pl: Run my_script.pl by calling perl: 8/31/2017 Introduction to Perl Basics I 10 print Hello World!\n; perl ./my_script.pl Option 4: For a small script with several lines, you can run it directly on the command line: perl -e print Hello World!\n;

Perl's creator, Larry Wall, announced it the next day in his State of the Onion address. Most notably, he said "Perl 6 is going to be designed by the community." Everyone thought that Perl 6 would be the version after the just-released Perl v5.6. That didn't happen, but that's why "Perl" was in the name "Perl 6."

tutorial Sorry about that but I have to keep my tutorial's example scripts short and to the point Finally, this is a tutorial for Perl/Tk only I will not be teaching perl here So if you know perl, continue But if you are a beginner to perl, I would recommend that you read my perl tutorial

Run Perl Script Option 3: Create a Perl script my_script.pl: Run my_script.pl by calling perl: 8/31/2017 Introduction to Perl Basics I 10 print Hello World!\n; perl ./my_script.pl Option 4: For a small script with several lines, you can run it directly on the command line: perl -e print Hello World!\n;

Introduction to Perl Pinkhas Nisanov. Perl culture Perl - Practical Extraction and Report Language Perl 1.0 released December 18, 1987 by Larry Wall. Perl culture Perl Poems BEFOREHAND: close door, each window & exit; wait until time. open spellbook, study, read (scan, select, tell us);