SlideShare una empresa de Scribd logo

Perl6 signatures, types and multicall

Slides from my talk at TPC Glasgow 2018.

Perl6 signatures, types and multicall

Slides from my talk at TPC Glasgow 2018.

Perl6 signatures, types and multicall

1 de 43
Descargar para leer sin conexión
Perl6 Signatures,
Types and Multicall
About Me
● Simon Proctor
● Scimon in many places
● Senior Dev at Zoopla (we’re hiring)
● simon.proctor@gmail.com
Part 1 : Signatures
No Signature
sub foo {
@_.say;
}
● Should be familiar to Perl devs
● All arguments put into lexical @_ array
● @_ array only populated with arguments in this case only
● I would not encourage using this
No Signature (Note)
sub foo {
@_.say;
}
foo( A => 1 );
*ERRORS*
foo( ( A => 1 ) );
[A => 1]
When calling a sub (or method)
a Pair using either
A => 1 or :A(1) syntax will be
treated as a named argument.
In Perl6 => is not just a fat
comma.
Empty Signature
sub foo() {
say “I take orders from no one”;
}
● Specifically states this subroutine takes no arguments.
● Will error (generally at compile time) if called with arguments.
● Not just constants
○ Variables in outer scope available
○ State variables for generators

Recomendados

Más contenido relacionado

La actualidad más candente

Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20Max Kleiner
 
python Function
python Function python Function
python Function Ronak Rathi
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHPAndrew Kandels
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Rick Copeland
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunctionADARSH BHATT
 
Functions in python
Functions in pythonFunctions in python
Functions in pythonIlian Iliev
 
Regular Expressions in PHP, MySQL by programmerblog.net
Regular Expressions in PHP, MySQL by programmerblog.netRegular Expressions in PHP, MySQL by programmerblog.net
Regular Expressions in PHP, MySQL by programmerblog.netProgrammer Blog
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perlsana mateen
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehmanNauman Rehman
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsPhilip Schwarz
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl ProgrammingUtkarsh Sengar
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perlsana mateen
 
String variable in php
String variable in phpString variable in php
String variable in phpchantholnet
 

La actualidad más candente (20)

Maxbox starter20
Maxbox starter20Maxbox starter20
Maxbox starter20
 
python Function
python Function python Function
python Function
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHP
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Regular expressionfunction
Regular expressionfunctionRegular expressionfunction
Regular expressionfunction
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Learning Grep
Learning GrepLearning Grep
Learning Grep
 
Regular Expressions in PHP, MySQL by programmerblog.net
Regular Expressions in PHP, MySQL by programmerblog.netRegular Expressions in PHP, MySQL by programmerblog.net
Regular Expressions in PHP, MySQL by programmerblog.net
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Subroutines in perl
Subroutines in perlSubroutines in perl
Subroutines in perl
 
Unit vii wp ppt
Unit vii wp pptUnit vii wp ppt
Unit vii wp ppt
 
A regex ekon16
A regex ekon16A regex ekon16
A regex ekon16
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
 
Ad hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and CatsAd hoc Polymorphism using Type Classes and Cats
Ad hoc Polymorphism using Type Classes and Cats
 
Perl 101 - The Basics of Perl Programming
Perl  101 - The Basics of Perl ProgrammingPerl  101 - The Basics of Perl Programming
Perl 101 - The Basics of Perl Programming
 
Awk programming
Awk programming Awk programming
Awk programming
 
Scalar expressions and control structures in perl
Scalar expressions and control structures in perlScalar expressions and control structures in perl
Scalar expressions and control structures in perl
 
String variable in php
String variable in phpString variable in php
String variable in php
 
Hadoop Pig
Hadoop PigHadoop Pig
Hadoop Pig
 

Similar a Perl6 signatures, types and multicall

Similar a Perl6 signatures, types and multicall (20)

PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
PHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look AheadPHP 5.3 And PHP 6 A Look Ahead
PHP 5.3 And PHP 6 A Look Ahead
 
SymfonyCon 2017 php7 performances
SymfonyCon 2017 php7 performancesSymfonyCon 2017 php7 performances
SymfonyCon 2017 php7 performances
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
What's New in PHP 5.5
What's New in PHP 5.5What's New in PHP 5.5
What's New in PHP 5.5
 
What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3What's new, what's hot in PHP 5.3
What's new, what's hot in PHP 5.3
 
Apache pig
Apache pigApache pig
Apache pig
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
Designing Ruby APIs
Designing Ruby APIsDesigning Ruby APIs
Designing Ruby APIs
 
React Js Training In Bangalore | ES6 Concepts in Depth
React Js Training   In Bangalore | ES6  Concepts in DepthReact Js Training   In Bangalore | ES6  Concepts in Depth
React Js Training In Bangalore | ES6 Concepts in Depth
 
Fantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOFFantom on the JVM Devoxx09 BOF
Fantom on the JVM Devoxx09 BOF
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Licão 13 functions
Licão 13 functionsLicão 13 functions
Licão 13 functions
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 

Más de Simon Proctor

An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to RakuSimon Proctor
 
Building a raku module
Building a raku moduleBuilding a raku module
Building a raku moduleSimon Proctor
 
Perl6 operators and metaoperators
Perl6   operators and metaoperatorsPerl6   operators and metaoperators
Perl6 operators and metaoperatorsSimon Proctor
 
Perl 6 command line scripting
Perl 6 command line scriptingPerl 6 command line scripting
Perl 6 command line scriptingSimon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tourSimon Proctor
 

Más de Simon Proctor (9)

An introduction to Raku
An introduction to RakuAn introduction to Raku
An introduction to Raku
 
Building a raku module
Building a raku moduleBuilding a raku module
Building a raku module
 
Multi stage docker
Multi stage dockerMulti stage docker
Multi stage docker
 
Phasers to stunning
Phasers to stunningPhasers to stunning
Phasers to stunning
 
Perl6 operators and metaoperators
Perl6   operators and metaoperatorsPerl6   operators and metaoperators
Perl6 operators and metaoperators
 
24 uses for perl6
24 uses for perl624 uses for perl6
24 uses for perl6
 
Perl 6 command line scripting
Perl 6 command line scriptingPerl 6 command line scripting
Perl 6 command line scripting
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 
Perl6 a whistle stop tour
Perl6 a whistle stop tourPerl6 a whistle stop tour
Perl6 a whistle stop tour
 

Último

research powerpoint on the science fiction tv series manifest.
research powerpoint on the science fiction tv series manifest.research powerpoint on the science fiction tv series manifest.
research powerpoint on the science fiction tv series manifest.17pmat213
 
Blockchain Interoperability
Blockchain InteroperabilityBlockchain Interoperability
Blockchain InteroperabilityLiveplex
 
Mendix vs. OutSystems - Version Control
Mendix vs. OutSystems - Version ControlMendix vs. OutSystems - Version Control
Mendix vs. OutSystems - Version ControlLeon Verster
 
Embracing Disruption: Adding a Bit of Chaos to Help You Grow
Embracing Disruption: Adding a Bit of Chaos to Help You GrowEmbracing Disruption: Adding a Bit of Chaos to Help You Grow
Embracing Disruption: Adding a Bit of Chaos to Help You GrowPaul Balogh
 
Calicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSL
Calicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSLCalicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSL
Calicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSLAnoopRamachandran13
 
Dataliva Company Brief 2024
Dataliva Company Brief 2024Dataliva Company Brief 2024
Dataliva Company Brief 2024Mustafa Kuğu
 
AMS_00 FTBE_0126_2024. .pptx
AMS_00 FTBE_0126_2024.             .pptxAMS_00 FTBE_0126_2024.             .pptx
AMS_00 FTBE_0126_2024. .pptxFinTech Belgium
 
DevFest Warsaw
DevFest WarsawDevFest Warsaw
DevFest WarsawGDSC PJATK
 
Intra-body nano-network - Brief summary by Mik Andersen
Intra-body nano-network - Brief summary by Mik AndersenIntra-body nano-network - Brief summary by Mik Andersen
Intra-body nano-network - Brief summary by Mik Andersenkrcdnsqxswifzizvzs
 
Mainframe Sort Operations: Gaining the Insights You Need for Peak Performance
Mainframe Sort Operations: Gaining the Insights You Need for Peak PerformanceMainframe Sort Operations: Gaining the Insights You Need for Peak Performance
Mainframe Sort Operations: Gaining the Insights You Need for Peak PerformancePrecisely
 
BOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdf
BOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdfBOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdf
BOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdfMichaelOLeary82
 
Wandavision opening sequence and analysis
Wandavision opening sequence and analysisWandavision opening sequence and analysis
Wandavision opening sequence and analysis17pmat213
 
HHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptx
HHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptxHHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptx
HHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptxHampshireHUG
 
web accessibility: why should I care? - with notes
web accessibility: why should I care? - with notesweb accessibility: why should I care? - with notes
web accessibility: why should I care? - with notesMana Sugiyoshi
 
Onboarding slides for UiPath Meetup - Welcome
Onboarding slides for UiPath Meetup - WelcomeOnboarding slides for UiPath Meetup - Welcome
Onboarding slides for UiPath Meetup - WelcomeAndreeaTom
 
Material of Course Juniper JNCIA JUNOS Day1
Material of Course Juniper JNCIA JUNOS Day1Material of Course Juniper JNCIA JUNOS Day1
Material of Course Juniper JNCIA JUNOS Day1Foryanto J. Wiguna
 
Smartphone-Based Teaching System for Neonate Soothing Motions
Smartphone-Based Teaching System for Neonate Soothing MotionsSmartphone-Based Teaching System for Neonate Soothing Motions
Smartphone-Based Teaching System for Neonate Soothing Motionssugiuralab
 
The Top Outages of 2023: Analysis and Takeaways
The Top Outages of 2023: Analysis and TakeawaysThe Top Outages of 2023: Analysis and Takeaways
The Top Outages of 2023: Analysis and TakeawaysThousandEyes
 
Christmas Coding
Christmas CodingChristmas Coding
Christmas CodingGDSC PJATK
 

Último (20)

research powerpoint on the science fiction tv series manifest.
research powerpoint on the science fiction tv series manifest.research powerpoint on the science fiction tv series manifest.
research powerpoint on the science fiction tv series manifest.
 
Blockchain Interoperability
Blockchain InteroperabilityBlockchain Interoperability
Blockchain Interoperability
 
Mendix vs. OutSystems - Version Control
Mendix vs. OutSystems - Version ControlMendix vs. OutSystems - Version Control
Mendix vs. OutSystems - Version Control
 
Embracing Disruption: Adding a Bit of Chaos to Help You Grow
Embracing Disruption: Adding a Bit of Chaos to Help You GrowEmbracing Disruption: Adding a Bit of Chaos to Help You Grow
Embracing Disruption: Adding a Bit of Chaos to Help You Grow
 
Calicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSL
Calicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSLCalicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSL
Calicut MuleSoft Meetup Group - #13 Implementing One-Way and Two-Way SSL
 
Dataliva Company Brief 2024
Dataliva Company Brief 2024Dataliva Company Brief 2024
Dataliva Company Brief 2024
 
AMS_00 FTBE_0126_2024. .pptx
AMS_00 FTBE_0126_2024.             .pptxAMS_00 FTBE_0126_2024.             .pptx
AMS_00 FTBE_0126_2024. .pptx
 
DevFest Warsaw
DevFest WarsawDevFest Warsaw
DevFest Warsaw
 
Intra-body nano-network - Brief summary by Mik Andersen
Intra-body nano-network - Brief summary by Mik AndersenIntra-body nano-network - Brief summary by Mik Andersen
Intra-body nano-network - Brief summary by Mik Andersen
 
Mainframe Sort Operations: Gaining the Insights You Need for Peak Performance
Mainframe Sort Operations: Gaining the Insights You Need for Peak PerformanceMainframe Sort Operations: Gaining the Insights You Need for Peak Performance
Mainframe Sort Operations: Gaining the Insights You Need for Peak Performance
 
BOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdf
BOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdfBOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdf
BOS K8S Meetup - Finetuning LLama 2 Model on GKE.pdf
 
Wandavision opening sequence and analysis
Wandavision opening sequence and analysisWandavision opening sequence and analysis
Wandavision opening sequence and analysis
 
GitHub Copilot-vijaymohire
GitHub Copilot-vijaymohireGitHub Copilot-vijaymohire
GitHub Copilot-vijaymohire
 
HHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptx
HHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptxHHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptx
HHUG-Jan-2024-Can AI help meet your 2024 challenges_.pptx
 
web accessibility: why should I care? - with notes
web accessibility: why should I care? - with notesweb accessibility: why should I care? - with notes
web accessibility: why should I care? - with notes
 
Onboarding slides for UiPath Meetup - Welcome
Onboarding slides for UiPath Meetup - WelcomeOnboarding slides for UiPath Meetup - Welcome
Onboarding slides for UiPath Meetup - Welcome
 
Material of Course Juniper JNCIA JUNOS Day1
Material of Course Juniper JNCIA JUNOS Day1Material of Course Juniper JNCIA JUNOS Day1
Material of Course Juniper JNCIA JUNOS Day1
 
Smartphone-Based Teaching System for Neonate Soothing Motions
Smartphone-Based Teaching System for Neonate Soothing MotionsSmartphone-Based Teaching System for Neonate Soothing Motions
Smartphone-Based Teaching System for Neonate Soothing Motions
 
The Top Outages of 2023: Analysis and Takeaways
The Top Outages of 2023: Analysis and TakeawaysThe Top Outages of 2023: Analysis and Takeaways
The Top Outages of 2023: Analysis and Takeaways
 
Christmas Coding
Christmas CodingChristmas Coding
Christmas Coding
 

Perl6 signatures, types and multicall

  • 2. About Me ● Simon Proctor ● Scimon in many places ● Senior Dev at Zoopla (we’re hiring) ● simon.proctor@gmail.com
  • 3. Part 1 : Signatures
  • 4. No Signature sub foo { @_.say; } ● Should be familiar to Perl devs ● All arguments put into lexical @_ array ● @_ array only populated with arguments in this case only ● I would not encourage using this
  • 5. No Signature (Note) sub foo { @_.say; } foo( A => 1 ); *ERRORS* foo( ( A => 1 ) ); [A => 1] When calling a sub (or method) a Pair using either A => 1 or :A(1) syntax will be treated as a named argument. In Perl6 => is not just a fat comma.
  • 6. Empty Signature sub foo() { say “I take orders from no one”; } ● Specifically states this subroutine takes no arguments. ● Will error (generally at compile time) if called with arguments. ● Not just constants ○ Variables in outer scope available ○ State variables for generators
  • 7. Empty Signature (methods) method foo() { say self.bar; } ● Object methods with an empty signature also error if called with arguments. ● Have access to self (and the $ alias) though.
  • 8. Positional Arguments sub foo($a,$b,$c) { say “$a : $b : $c”; } ● Maps arguments to lexical variables based on position ● Errors unless the exact number of arguments are passed
  • 9. Positional Arguments (methods) method foo($foo: $a) { say “{$foo.attr} : $a”; } ● Optional initial argument separated with : defines another reference for self that can be used in the method ● Useful with where clauses and multi methods ● Also can be used to specify class methods
  • 10. Positional Arguments : Defaults and optional sub foo($a, $b?, $c=5, $d=$c*2) { say “$a : $b : $c : $d”; } foo(1,2) 1 : 2 : 5 : 10 ● Any positions not filled will get their defaults ● Defaults are calculated for each call ● Defaults can be based on values earlier in the argument list. ● Mark an argument as optional with ? after the name.
  • 11. Positional Arguments : Sigils sub foo(@a) { say @a; } foo(1,2) Errors foo( [1,2] ) [1,2] @ and % sigils are type signifiers for Positional and Associative roles.
  • 12. Positional Arguments : Flattening Slurpy sub foo(*@a) { say @a; } foo(1,2) [1,2] foo( 1,[2,3] ) [1,2,3] Single * will slurp and flatten all remaining positional arguments. foo(1,(2,3)) [1,2,3] foo(1,{2 => 3}) [1,{2=>3}]
  • 13. Positional Arguments : Non Flattening Slurpy sub foo(**@a) { say @a; } foo(1,2) [1,2] foo( 1,[2,3] ) [1,[2,3]] Double * will slurp all remaining positional arguments but not flatten lists or hashes. foo(1,(1,2)) [1,(1,2)] foo(1,{2 => 3}) [1,{2=>3}]
  • 14. Positional Arguments : Single Rule Slurpy sub foo(+@a) { say @a; } foo(1) [1] foo( [2,3] ) [2,3] A + slurpy will flatten a single iterable object into the arguments array. Otherwise it works like **. foo(1,[2,3]) [1,[2,3]] foo(1,{2 => 3}) [1,{2=>3}]
  • 15. Positional Arguments : Combinations sub foo($a,*@b) { say “$a : {@b.perl}”; } foo(1) 1 : [] foo( 1,[2,3] ) 1 : [2,3] ● You can combine positional and slurpy argument. ● The slurpy has to come last. ● You can only have one slurpy argument. foo(1,2,3) 1 : [2,3] foo(1,2,3,{a => 5}) 1:[2,3,:a(5)]
  • 16. Named Arguments sub foo(:$a,:$b!) { say “$a & $b”; } foo(a=>“b”,b=>“c”) b & c foo(:a<bar>) Required named parameter 'b' not passed ● Define named arguments with a ‘:’ in front of the lexical variable. ● Named arguments are not required. ● Append the name with ! to make it required. foo(:b<bar>) & bar Use of uninitialized value $a of type Any in string context.
  • 17. Alternate Named Arguments sub foo(:bar(:$b)) { say $b; } foo(b=>“a”) a foo(:bar<bar>) bar ● Alternate argument names can be nested multiple times : ○ :$val ○ :v($val) ■ :v() in call ○ :v(:$val) ■ :v() or :val() ○ :valid(:v(:$val)) ● All referenced as $val in the sub ● Useful for sub MAIN
  • 18. Combining Named and Positional Arguments sub foo($a,:$b) { say $a if $b; } foo(“Hi”,:b) Hi foo(“Crickets”) ● Positional arguments have to be defined before named. ● You can combine a slurpy positional and named arguments.
  • 19. Named Arguments : Slurpy Hash sub foo(*%a) { say %a; } foo(a=>b) {a => b} Using * on a hash will take all the named argument pairs and put them in the given hash. foo( b => [5,6], :a(b) ) {b => [5,6], a => b} foo( :a, :!b ) { a => True, b => False }
  • 20. Constraints (Part 1) sub foo($a where * > 10) { say $a; } foo(5); Errors The where clause needs to be true or the system will throw an Exception. You can CATCH this normally. Where clauses can be chained: where * > 10 where *.is-prime foo(11); 11
  • 21. Constraints (Part 2) sub foo($a where * > 10 where .is-prime) { say $a; } foo(5); Errors foo(12); Errors Where clauses can be chained foo(13); 13
  • 22. Sub Signatures sub foo(@a ($b, $c)){ say “$b : $c”; } foo([1,2]); 1 : 2 foo(1,2); Errors foo([1,2,3]); Errors Positional and Associative objects can have sub signatures assigned to them. Sub signatures can be nested. (But you might want to think if there’s an easier plan)
  • 23. Captures my $c = (1,2,3); sub foo(*@in) { [+] @in } say foo(|$c); 6 Signatures and Captures are both first class objects. You can introspect signatures to get information about them. Captures can be stored and reused and examined as well. For further information I’d advise looking at the docs: https://docs.perl6.org/type/Signature
  • 24. Part 2 : Types
  • 25. Simple Types sub foo(Int $a) { say $a; } foo(5) 5 foo(“bob”) Errors Depending on how you are calling your function you may get a run time or a compile time error. Types can be built in or newly created Classes (or Roles). Types can be applied to named or positional parameters
  • 26. Type Coercion sub foo(Int() $a) { say $a; } If you want allow anything that can be cast to the given type. Note this will only ever give runtime errors. foo(5.5) 5 foo(5e5) 50000 foo(5) 5 foo(“bob”) Errors foo(“5”) 5
  • 27. Advanced Type Coercion sub foo(Int(Numeric) $a) { say $a; } Type() == Type(Any) for coercion. You can give a more specific type if required though. foo(5.5) 5 foo(5e5) 50000 foo(5) 5 foo(“bob”) Errors foo(“5”) Errors
  • 28. Return Type Constraints sub foo(Int $a --> Int) { return $a * 2; } Return types can have constraints added. my Int $b = foo(5); say $b; 10 my Rat $e = foo(5); Errors say foo(5); 10 $a = foo(5); say $a 10
  • 29. Constraints (Part 3) sub foo(Int $a where * > 5) { say $a; } Type constraints can be combined with where clauses. foo(6) 6 foo(6.5) Errors foo(5) Errors foo(5.5) Errors
  • 30. Subsets (Named Type Constraints) subset IntOver5 of Int where * > 5; sub foo(IntOver5 $a) { say $a; } Subset lets you name a type constraint You can add one or more where clause as well. foo(6) 6 foo(6.5) Errors foo(5) Errors foo(5.5) Errors
  • 31. Subsets (Multiple Types) subset IntOrRat of Numeric where { $_ ~~ Int|Rat}; sub foo(IntOrRat $a) { say $a; } You can only constrain a variable to one type. But you can use subsets to allow multiple input types. Note you can’t use a wherever block due to precedence for Junctions.foo(6e5) Errors foo(6+i) Errors foo(5) 5 foo(5.5) 5.5
  • 32. Type Captures sub foo(::T $a, T $b ) { say “{$a} and {$b} are type {T.perl}” } Type captures allow you to capture the type of the input and access it in the containing block. You can also reference it elsewhere in the signature and add constraints. foo(5,6) 5 and 6 are type Int foo(5.5,6.7) 5.5 and 6.7 are type Rat foo(“a”,”b”) a and b are type Str foo(“5”,5) Errors
  • 33. Part 3 : Multi Call
  • 34. Basic Multi Call multi sub foo(Int $a) { $a; } multi sub foo(Rat $a) { round($a); } If you define a subroutine or method as multi then the system will pick the signature that best matches the input variables. Return constraints are NOT included in the matching. say foo(“a”); Errors say foo(“1”); Errors say foo(5); 5 say foo(4.5); 5;
  • 35. Constants multi sub fib(0) {1} multi sub fib(1) {1} multi sub fib(UInt $f) { fib($f-1) + fib($f-2) } Your type constraints can include constants. Note that a recursive subroutine like this will not be very performant. sub fib($x) { state @f = 1,1,*+*...*; @f[$x]; } say fib(1); 1 say fib(20); 10946
  • 36. Prototypes proto foo(Int $a,|) {*} multi foo($a, Int $b) { $a+$b} multi foo($a, Rat $b) { $a+$b.denominator } If your subs or methods share inputs you can declare their constraints in the proto. * is replaced with the code for the final multi | is the anonymous capture representing the other variables. Note lone multi implies sub say foo(1,1); 2 say foo(1,1.5); 3
  • 37. Only only sub foo($a) { $a; } … multi sub foo($a,$b) { $a ~~ $b } Declaring a sub or method as only will raise an Exception if the same name is used within the same namespace. It’s not required but it’s good defensive programing. Errors
  • 38. Use Case : MAIN use Library; my %*SUB-MAIN-OPTS = :named-anywhere; multi MAIN( “action” ) { Library::action(); } multi MAIN( “action”, Bool :$help where ?* ) { Library::document_action(); } Using a Library gives you bytecode compiled data. MAIN takes command line args and maps them to positional and associative. %*SUB-MAIN-OPTS = :named-anywhere allows inputs types to mingle.
  • 39. Example : App::Mi6 use v6; use App::Mi6; my %*SUB-MAIN-OPTS = :named-anywhere; my $app = App::Mi6.new; multi MAIN("version") { say $app.^ver; } multi MAIN("new", $module) { $app.cmd("new", $module); } multi MAIN("build") { $app.cmd("build"); } multi MAIN("release", Bool :$keep) { $app.cmd("release", :$keep); } multi MAIN("test", *@file, Bool :v(:$verbose), Int :j(:$jobs)) { $app.cmd("test", @file, :$verbose, :$jobs); } multi MAIN("dist") { $app.cmd("dist"); } multi MAIN("upload") { die "`mi6 upload` is removed, please execute `mi6 release` instead.n"; } multi MAIN("help") { USAGE(); } multi MAIN(:h(:$help)!) { USAGE(); } sub USAGE { require Pod::To::Text; ::("Pod::To::Text").render($=pod).say; exit 1; }
  • 40. Bonus Slide : Operators sub infix:<£==> ( $gbp, $usd ) { $gbp =~= ( $usd / .7862 ) } say 100 £== 78.62; True sub prefix:<£> ( $gbp ) { “${$gbp * .7862}” } say £100; “$78.62” sub postfix:<!> ( UInt $num ) { [*] (1..$num) } say 5!; 120 sub circumfix:<FOO BAR> ( @a ) { “BAR {@a.reverse.join(‘ ’)} FOO” } say FOO 1..5 BAR;BAR 5 4 3 2 1 FOO sub postcircumfix:<d d> ( $year, $day ) { Date.new( “{$year}-01-01” ) + $day } say 1970d 100 d; 1970-04-11
  • 41. Bonus Slide : Sub / Method Traits is assoc : Define an operators associativity (left, right, chain, list or non) is tighter, is looser, is equiv : Define an operators precedence is pure : Given a set of arguments will always return the same result. Do not use if you have side effects as this can be inlined. is export : Marks a sub as to be exported from the current namespace (you can specify when) is rw : The return value can be assigned to directly. is DEPRECATED : Flag your sub as deprecated, warnings will be raised if you use it is hidden-from-backtrace : Skip this function when giving a backtrace