The Perl 6 Express - Jonathan Worthington

2y ago
35 Views
3 Downloads
1.86 MB
111 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Kian Swinton
Transcription

The Perl 6ExpressJonathan WorthingtonNordic Perl Workshop 2009

The Perl 6 ExpressAbout Me Originally from England Currently living in Slovakia Like curry, heavy metal and travelling

The Perl 6 ExpressAbout Me Originally from England Currently living in Slovakia Like curry, heavy metal and travelling

The Perl 6 ExpressSlovakia The most common question I get askedabout Slovakia

The Perl 6 ExpressSlovakia The most common question I get askedabout Slovakia"Where on earth is that?"

The Perl 6 ExpressSlovakia In Central Europe; borders Austria,Hungary, Ukraine, Poland and theCzech Republic

The Perl 6 ExpressSlovakia/Scandinavia reLanguage FamilySlavicNorthern GermanicHas Many BeautifulAreasYesYesEating Raw FishConsidered NormalNoYesBeer priceCheapOMG WTF?!Have opium as aChristmas traditionYesNo

The Perl 6 ExpressAbout This Talk A look at some of the changes and newfeatures in Perl 6, the next version ofthe Perl programming language that iscurrently in developmentMore of an overview of what's on offerthan an in-depth tutorialSticks to code that you can run on aPerl 6 implementation today (Rakudo)

The Perl 6 ExpressAbout This Talk Will be two sections of an hour each,with a ten-minute break in the middle First half is mostly basic stuff Second half is mostly not-so-basic stuff (But hey, at least none of it is VisualBasic stuff)Feel free to ask questions at any pointyou don't understand

The Perl 6 ExpressA LittleBackground

The Perl 6 ExpressWhat is Perl 6? Perl 6 is a ground-up re-design and reimplementation of the languageNot backward compatible with Perl 5 Opportunity to add, update and fixmany thingsThere will be a code translator andyou will be able to use many Perl 5modules from Perl 6

The Perl 6 ExpressLanguage vs. Implementation In Perl 5, there was only oneimplementation of the languageOther languages have many choicesPerl 6 is the name of the language, butnot of any particular implementation(just like C)Various implementation effortsunderway

The Perl 6 ExpressRakudo An implementation of Perl 6 on theParrot Virtual Machine VM aiming to run many dynamiclanguages and allow interoperabilitybetween themImplemented partly in NQP (a subset ofPerl 6), partly in Perl 6 (some built-ins),partly in Parrot Intermediate Languageand a little bit of C

The Perl 6 ExpressWhy "Rakudo"? Suggested by Damian ConwaySome years ago, Con Wei Senseiintroduced a new martial art in Japannamed "The Way Of The Camel"In Japanese, this is "Rakuda-do"The name quickly became abbreviatedto "Rakudo", which also happens tomean "paradise" in Japanese

The Perl 6 ExpressHow To Build Rakudo Clone the source from GITgit://github.com/rakudo/rakudo.gitBuild it (builds Parrot for you):perl Configure.pl --gen-parrotmake perl6 Run it on the command line, with ascript or in interactive modeperl6 –e "say 'Hello, world!'"perl6 script.p6perl6

The Perl 6 ExpressRakudo Progress10300 passingspecificationtests

The Perl 6 ExpressVariables

The Perl 6 ExpressDeclaring Variables As in Perl 5, declare lexical variableswith mymy answer 42;my city 'Oslo';my very approx pi 3.14; Unlike in Perl 5, by default you mustdeclare your variables (it's like havinguse strict on by default)You can also use our for packagevariables, just like in Perl 5

The Perl 6 ExpressSigils All variables have a sigilUnlike in Perl 5, the sigil is just part ofthe name ( a[42] is now @a[42]).The sigil defines a kind of "interfacecontract" – promises about what youcan do with this variable Anything with @ sigil can be indexedinto positionally, using [ ]

The Perl 6 ExpressArrays Hold zero or more elements and allowyou to index into them with an integer# Declare an array.my @scores;# Or initialize with some initial values.my @scores 52,95,78;my @scores 52 95 78 ; # The same# Get and set individual elements.say @a[1]; # 95@a[0] 100;say @a[0]; # 100

The Perl 6 ExpressHashes Hold zero or more elements, with keysof any type# Declare a hash.my %ages;# Set values.%ages Fred 19;my name 'Harry';%ages{ name} 23;# Constant keys# More complex ones# Get an individual element.say %ages Harry ;# 23

The Perl 6 ExpressState Variables Are initialised the first time a block isenteredRetain their values between invocationsof the blocksub count {state count 1;say count ;}count() for 1.3;123

The Perl 6 ExpressState Variables However, if the block is cloned (forexample, when you take a closure) thenthe state is lostsub create counter {return {state count 1;say count ;};}my c1 create counter();my c2 create counter(); c1(); c1(); c2(); c2(); c2();# 1 2# 1 2 3

The Perl 6 ExpressIteration

The Perl 6 ExpressThe for Loop To IterateIn Perl 6, the for loop is used to iterateover anything that provides an iterator By default, puts the variable into The following example will print all of theelements in the @scores arraymy @scores 52 95 78 ;for @scores {say ;}

The Perl 6 ExpressThe for Loop To Iterate Anything between { } is just a blockIn Perl 6, a block can take parameters,specified using the - syntaxmy @scores 52 95 78 ;for @scores - score {say score;} Here, we are naming the parameter tothe block that will hold the iterationvariable

The Perl 6 ExpressThe for Loop To Iterate .kv method of a hash returns keys andvalues in a listA block can take multiple parameters,so we can iterate over the keys andvalues togethermy %ages (Fred 45, Bob 33);for %ages.kv - name, age {say " name is age years old";}Fred is 45 years oldBob is 33 years old

The Perl 6 ExpressThe loop Loop The for loop is only for iteration now;for C-style for loops, use the loopkeywordloop (my i 1; i 42; i ) {say i;} Bare loop block is an infinite looploop {my cur pos get position();update trajectory( target, cur pos);}

The Perl 6 ExpressConditionals

The Perl 6 ExpressThe if Statement You can use the if elsif else styleconstruct in Perl 6, as in Perl 5if foo 42 {say "The answer!";} elsif foo 0 {say "Nothing";} else {say "Who knows what";} However, you can now omit theparentheses around the condition

The Perl 6 ExpressChained Conditionals Perl 6 supports "chaining" ofconditionals, so instead of writing:if roll 1 && roll 6 {say "Valid dice roll"}You can just write:if 1 roll 6 {say "Valid dice roll"}

The Perl 6 ExpressChained Conditionals You are not limited to chaining just twoconditionalsif 1 roll1 roll2 6 {say "Doubles!"} Here we check that both roles of thedice gave the same value, and that bothof them are squeezed between 1 and 6,inclusive

The Perl 6 ExpressSubroutines

The Perl 6 ExpressParameters You can write a signature on a subSpecifies the parameters that it expectsto receiveUnpacks them into variables for yousub order beer( type, how many) {say " how many pints of type, please";}order beer('Tuborg', 5);5 pints of Tuborg, please

The Perl 6 ExpressAuto-Referencing Arrays and hashes can be passedwithout having to take references toprevent them from flatteningsub both elems(@a, @b) {say @a.elems;say @b.elems;}my @x 1,2,3;my @y 4,5;both elems(@x, @y);32

The Perl 6 ExpressOptional Parameters Parameters can be optionalWrite a ? after the name of theparameter to make it sosub speak( phrase, how loud?) { . } Alternatively, give it a default valuesub greet( name, greeting 'Hej') {say " greeting, name";}greet('Anna');# Hej, Annagreet('Lenka', 'Čau');# Čau, Lenka

The Perl 6 ExpressNamed Parameters Named parameters are also availablesub catch train(: number!, : car, : place) {my platform find platform( number);walk to( platform);find place( car, place);}catch train(number '005',place 23car 5,); Optional by default; use ! to require

The Perl 6 ExpressSlurpy Parameters For subs taking a variable number ofarguments, use slurpy parameterssub say double(*@numbers) {for @numbers {say 2 * ;}}say double();# No outputsay double(21);# 42\nsay double(5,7,9);# 10\n14\n18\n Use *%named for named parameters

The Perl 6 ExpressObjectOrientation

The Perl 6 ExpressEverything Is An ObjectYou can treat pretty much everything asan object if you want For example, arrays have an elemsmethod to get the number of elements my @scores 52 95 78 ;say @scores.elems; # 3 Can also do push, pop, etc. as methods@scores.push(88);say @scores.shift; # 52

The Perl 6 ExpressClasses Basic class definitions in Perl 6 are notso unlike many other languages Attributes specifying state Methods specifying behaviourclass Dog {has .name;has @!paws;method bark() {say "w00f";}}

The Perl 6 ExpressAttributes All attributes are named !foo (or@!foo, %!foo, etc)Declaring an attribute as .foogenerates an accessor method Adding is rw makes it a mutatormethod too has !brain;# Privatehas .color;# Accessor onlyhas .name is rw; # Accessor and mutator

The Perl 6 ExpressMethods Automatically take the invocant andmake it accessible using the selfkeywordmethod be angry() {self.bark() for 1.10;} Methods are all virtual (so they overrideanything of the same name in a parentclass; exception: multi-methods, cometo tomorrow's talk )

The Perl 6 ExpressInheritance Done using the is keywordclass Puppy is Dog {method bark() {say "yap";}method chew( item) { item.damage;}} # an override# a new methodMultiple inheritance also possibleclass Puppy is Dog is Pet { }

The Perl 6 ExpressDelegation The handles keyword specifies thatan attribute handles certain methodshas !brain handles 'think';has !mouth handles bite eat drink ; You can use pairs to rename themhas !brain handles :think('use brain') Really all the compiler is doing isgenerating some "forwarder" methodsfor you

The Perl 6 ExpressDelegation If you write anything else after handles,the method name is smart-matchedagainst itCan write a regex has !butt handles /poo [ph] /; Or Whatever to delegate any methodsthat aren't otherwise defined by theclasshas !owner handles *;

The Perl 6 ExpressProto-objects When you declare a class, it installs aprototype object in the namespaceSomewhat like an "empty" instance ofthe objectYou can call methods on it which don'tdepend on the state; for example, thenew method to create a new instance:my fido Dog.new();

The Perl 6 ExpressInstantiation When you instantiate an object you canalso specify initial attribute valuesmy pet Puppy.new(name 'Rosey',color 'White');

The Perl 6 ExpressInstantiation When you instantiate an object you canalso specify initial attribute valuesmy pet Puppy.new(name 'Rosey',color 'White');w00f

The Perl 6 ExpressInstantiation When you instantiate an object you canalso specify initial attribute valuesmy pet Puppy.new(name 'Rosey',color 'White');w00fPerl 6 rocks!

The Perl 6 ExpressMetaclasses There is no Class classA proto-object points to the metaclass,making it available through the .HOW(Higher Order Workings) macroThis allows for introspection (getting alist of its methods, attributes, parents,roles that it does and so forth – all ofwhich can be further introspected)

The Perl 6 ExpressBasic I/O

The Perl 6 ExpressFile Handle ObjectsI/O is now much more OO The open function will now return an IOobject, which you call methods on to doinput/output open takes a named parameter tospecify the mode mymymymy fh fh fh fh append

The Perl 6 ExpressIterating Over A File Use the for loop to iterate over the filehandle, and the prefix operator to getan iterator from the file handlemy fh open("README", :r);for fh - line {say line;} fh.close(); Note that this auto-chomps: new linecharacters are removed from line

The Perl 6 ExpressWriting To A File To write to a file, just call the print andsay methods on the file handle objectmy fh open("example.txt", :w);for 1.10 - i { fh.say( i);} fh.close();

The Perl 6 ExpressStandard Handles STDIN is available as the global *IN,STDOUT as *OUT and STDERR as *ERRThey are just file handle objects, so it'spossible to call methods on them toread/write with themprint "Your name is: ";my name *IN.readline;say "Hi, name!";

The Perl 6 ExpressA Couple Of Handy Functions The slurp function lets you read anentire file into a scalarmy content slurp("data.txt"); The prompt function prints the givenmessage, then takes input from STDINmy name prompt "Your name is: ";say "OH HAI, { name.uc }!";

The Perl 6 Express Break

The Perl 6 ExpressTypes

The Perl 6 ExpressTypes In Perl 6, values know what kind ofthing they aresaysaysubsay 42.WHAT;"beer".WHAT;answer { return 42 }&answer.WHAT;# Int# Str# SubIncluding your own classesclass Dog { }my fido Dog.new();say fido.WHAT;# Dog

The Perl 6 ExpressTyped Variables We can refer to types in our code bynameFor example we can declare a variablecan only hold certain types of thingmy Int x 42; x 100; x "CHEEZBURGER"; # OK, 42 isa Int# OK, 100 isa Int# ErrorAgain, this works with types you havedefined in your own code too

The Perl 6 ExpressTyped Parameters Types can also be written in signaturesto constrain what types of parameterscan be passedsub hate(Str thing) {say " thing, you REALLY suck!";}hate("black hole"); # OKhate(42);# Type check failure

The Perl 6 ExpressSubtypes In Perl 6, you can take an existing typeand "refine" itsubset PositveInt of Int where { 0 } Pretty much any condition is fineThe condition will then be enforced perassignment to the variablemy PositiveInt x 5; # OK x -10;# Type check failure

The Perl 6 ExpressAnonymous Subtypes Like other types, you can use them onsubroutine parametersYou can also write an anonymousrefinement on a sub parametersub divide(Num a,Num b where { n ! 0 }) {return a / b;}say divide(126, 3); # 42say divide(100, 0); # Type check failure

The Perl 6 ExpressJunctions

The Perl 6 ExpressJunctions How often do you find yourself writingthings like:if drink eq 'wine' drink eq 'beer' {say "Don't get drunk on it!";} With junctions we can write this as:if drink eq 'wine' 'beer' {say "Don't get drunk on it!";} "wine" "beer" is a junction

The Perl 6 ExpressWhat are junctions? A junction can be used anywhere thatyou would use a single valueYou store it in a scalarBut, it holds and can act as many valuesat the same timeDifferent types of junctions havedifferent relationships between thevalues

The Perl 6 ExpressConstructing Junctions From Arrays You can construct junctions from arraysif all(@scores) pass mark {say "Everybody passed!";}if any(@scores) pass mark {say "Somebody passed";}if one(@scores) pass mark {say "Just one person passed";}if none(@scores) pass mark {say "EPIC FAIL";}

The Perl 6 ExpressJunction Auto-Threading If you pass a junction as a parameterthen by default it will auto-threadThat is, we will do the call once per itemin the junctionsub example( x) {say "called with x";}example(1 2 3);called with 1called with 2called with 3

The Perl 6 ExpressJunction Auto-Threading The default parameter type is AnyHowever, this is not the "top" type – thatis ObjectJunction inherits from Object, not Any

The Perl 6 ExpressJunction Auto-Threading The default parameter type is AnyHowever, this is not the "top" type – thatis ObjectJunction inherits from Object, not Anysub example(Junction x) {say "called with " x.perl;}example(1 2 3);example(42);called with any(1, 2, 3)Parameter type check failed for x in call to example

The Perl 6 ExpressJunction Auto-Threading The default parameter type is AnyHowever, this is not the "top" type – thatis ObjectJunction inherits from Object, not Anysub example(Object x) {say "called with " x.perl;}example(1 2 3);example(42);called with any(1, 2, 3)called with 42

The Perl 6 ExpressJunction Auto-Threading The return value that you get maintainsthe junction structuresub double( x) {return x * 2;}my x double(1 2 & 3);say x.perl;any(2, all(4, 6)) We thread the leftmost all or nonejunction first, then leftmost any or one

The Perl 6 ExpressMeta-Operators

The Perl 6 ExpressReduction Operators Takes an operator and an arrayActs as if you have written that operatorbetween all elements of the array# Add up all values in the array.my sum [ ] @values;# Compute 10 factorial (1 * 2 * 3 * * 10)my fact [*] 1.10;# Check a list is sorted numerically.if [ ] @values { }

The Perl 6 ExpressHyper Operators Takes an operator and does it for eachelement in an array, producing a newarray.my @round1 scores 10,18,9;my @round2 scores 14,5,13;say @round1 scores @round2 scores;# 24 23 22 Point "sharp end" outwards to replicatelast element if neededmy @doubled @in * 2;

The Perl 6 ExpressCross Operators Alone, produces all possiblepermutations of two or more listsmy @a 1,2;my @b 'a', 'b';say (@a X @b).perl; # ["1", "a", "1", "b",# "2", "a", "2", "b"] Can also take an operator and use it tocombine the elements together in someway, e.g. string concatenationsay (@a X @b).perl; # ["1a", "1b",# "2a", "2b"]

The Perl 6 ExpressRegexes AndGrammars

The Perl 6 ExpressWhat's Staying The Same You can still write regexes betweenslashes The ?, and * quantifiers ?, ? and *? lazy quantifiers ( ) is still used for capturing Character class shortcuts: \d, \w, \s for alternations (but semantics aredifferent; use for the Perl 5 ones)

The Perl 6 ExpressChange: Literals And Syntax Anything that is a number, a letter or theunderscore is a literal/foo 123/ # All literalsAnything else is syntaxYou use a backslash (\) to make literalssyntax and to make syntax literals/\ \w \ /# \ and \ are literals# \w is syntax

The Perl 6 ExpressChange: Whitespace Now what was the x modifier in Perl 5is the defaultThis means that spaces don't matchanything – they are syntax/abc//a b c/# matches abc# the same

The Perl 6 ExpressChange: Quoting Single quotes interpret all inside themas a literal (aside from \')Can re-write:/\ \w \ /As the slightly neater:/' ' \w ' '/ Spaces are literal in quotes too:/'a b c'/# requires the spaces

The Perl 6 ExpressChange: Grouping A non-capturing group is now writtenas [ ] (rather than (?: ) in Perl 5)/[foo bar baz] / Character classes are now [ ] ; theyare negated with -, combined with or- and ranges are expressed with ./ [A.Z] /# uppercase letter./ [A.Z] - [AEIOU] / # .but not a vowel/ [\w [-]] # anything in \w or a -

The Perl 6 ExpressChange: s and m The s and m modifiers are gone. now always matches anything,including a new line character Use \N for anything but a new line and always mean start and end ofthe string and always mean start and endof a line

The Perl 6 ExpressMatching To match against a pattern, use if event /\d**4/ { . } Negated form is ! if event ! /\d**4/ { fail "no year"; } / holds the match object; when used as astring, it is the matched textmy event "Nordic Perl Workshop 2009";if event /\d**4/ {say "Held in /"; # Held in 2009}

The Perl 6 ExpressNamed Regexes You can now declare a regex with aname, just like a sub or methodregex Year { \d**4 }; # 4 digits Then name it to match against it:if event / Year / { . }

The Perl 6 ExpressCalling Other Regexes You can "call" one regex from another,making it easier to build up complexpatterns and re-use regexesregex Year { \d**4 };regex Place { Nordic Ukrainian };regex Workshop { Place \s Perl \s Workshop \s Year };regex YAPC {'YAPC::' ['EU' 'NA' 'Asia'] \s Year };regex Event { Workshop YAPC };

The Perl 6 ExpressThe Match Object Can extract the year from a list of eventnames like this:for @events - ev

The Perl 6 Express About This Talk A look at some of the changes and new features in Perl 6, the next version of the Perl programming language that is currently in development More of an overview of what's on offer than an in-depth tutorial Sticks to c

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,

May 02, 2018 · D. Program Evaluation ͟The organization has provided a description of the framework for how each program will be evaluated. The framework should include all the elements below: ͟The evaluation methods are cost-effective for the organization ͟Quantitative and qualitative data is being collected (at Basics tier, data collection must have begun)

Silat is a combative art of self-defense and survival rooted from Matay archipelago. It was traced at thé early of Langkasuka Kingdom (2nd century CE) till thé reign of Melaka (Malaysia) Sultanate era (13th century). Silat has now evolved to become part of social culture and tradition with thé appearance of a fine physical and spiritual .

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

On an exceptional basis, Member States may request UNESCO to provide thé candidates with access to thé platform so they can complète thé form by themselves. Thèse requests must be addressed to esd rize unesco. or by 15 A ril 2021 UNESCO will provide thé nomineewith accessto thé platform via their émail address.

̶The leading indicator of employee engagement is based on the quality of the relationship between employee and supervisor Empower your managers! ̶Help them understand the impact on the organization ̶Share important changes, plan options, tasks, and deadlines ̶Provide key messages and talking points ̶Prepare them to answer employee questions

Dr. Sunita Bharatwal** Dr. Pawan Garga*** Abstract Customer satisfaction is derived from thè functionalities and values, a product or Service can provide. The current study aims to segregate thè dimensions of ordine Service quality and gather insights on its impact on web shopping. The trends of purchases have

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