SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
Perl6 Signatures
Everything you didn’t realise you wanted to know,
and a whole lot more!
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
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.
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 : eg. outer scope, state declarations
Empty Signature (methods)
method foo() {
say self.bar;
}
● Methods with an empty signature also error if called with
arguments.
● Have access to self (and the $ alias) though.
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
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
Positional Arguments : Defaults and optional
sub foo($a,$b?,$c = 5) {
say “$a : $b : $c”;
}
foo(1,2)
1 : 2 : 5
● Any positions not filled will get their defaults
● Mark an argument as optional with ? after the name.
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.
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}]
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}]
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}]
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)]
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.
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
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.
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 }
Bonus Slide : Types
sub num-in-country(:$num, :$ccode){...}
sub num-in-country(UInt :$num, Str :$ccode){...}
sub num-in-country(UInt :$num, Str :$ccode
where * ~~ /^ <[a..z]> ** 2 $/ ){...}
subset CCode of Str where * ~~ /^ <[a..z]> ** 2 $/;
sub num-in-country(UInt :$num, CCode :$ccode){...}
Sub coerced-type( Str() $a ) { say “$a could have been many...” }
Bonus Slide : Multi Call
subset Seven of Int where * == 7;
multi sub foo() { 'No args' }
multi sub foo(5) { 'Called with 5' }
multi sub foo(Seven $) { 'Called with 7' }
multi sub foo( *@a ) { '*@a' }
multi sub foo( $a ) { '$a' }
multi sub foo( Cool $b ) { 'Cool $b' }
multi sub foo( Int $b ) { 'Int $b' }
multi sub foo( Int $b where * > 0 ) { 'Int $b where * > 0' }

Más contenido relacionado

La actualidad más candente

Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP StringsAhmed Swilam
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrepTri Truong
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl   finer points ,pack&amp;unpack,eval,filesAdvanced perl   finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,filesShankar D
 
Php basics
Php basicsPhp basics
Php basicshamfu
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsingsanchi29
 
Declarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term RewritingDeclarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term RewritingGuido Wachsmuth
 
Strings in Python
Strings in PythonStrings in Python
Strings in Pythonnitamhaske
 
Declare Your Language: Syntactic (Editor) Services
Declare Your Language: Syntactic (Editor) ServicesDeclare Your Language: Syntactic (Editor) Services
Declare Your Language: Syntactic (Editor) ServicesEelco Visser
 
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
 
String variable in php
String variable in phpString variable in php
String variable in phpchantholnet
 
Pure and Declarative Syntax Definition: Paradise Lost and Regained
Pure and Declarative Syntax Definition: Paradise Lost and RegainedPure and Declarative Syntax Definition: Paradise Lost and Regained
Pure and Declarative Syntax Definition: Paradise Lost and RegainedGuido Wachsmuth
 
Processing Regex Python
Processing Regex PythonProcessing Regex Python
Processing Regex Pythonprimeteacher32
 
python Function
python Function python Function
python Function Ronak Rathi
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionEelco Visser
 

La actualidad más candente (20)

Antlr V3
Antlr V3Antlr V3
Antlr V3
 
Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Regular Expressions grep and egrep
Regular Expressions grep and egrepRegular Expressions grep and egrep
Regular Expressions grep and egrep
 
Advanced perl finer points ,pack&amp;unpack,eval,files
Advanced perl   finer points ,pack&amp;unpack,eval,filesAdvanced perl   finer points ,pack&amp;unpack,eval,files
Advanced perl finer points ,pack&amp;unpack,eval,files
 
Php basics
Php basicsPhp basics
Php basics
 
Intoduction to php strings
Intoduction to php  stringsIntoduction to php  strings
Intoduction to php strings
 
Syntax Definition
Syntax DefinitionSyntax Definition
Syntax Definition
 
Operator precedance parsing
Operator precedance parsingOperator precedance parsing
Operator precedance parsing
 
Declarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term RewritingDeclarative Semantics Definition - Term Rewriting
Declarative Semantics Definition - Term Rewriting
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Declare Your Language: Syntactic (Editor) Services
Declare Your Language: Syntactic (Editor) ServicesDeclare Your Language: Syntactic (Editor) Services
Declare Your Language: Syntactic (Editor) Services
 
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
 
Syntax Definition
Syntax DefinitionSyntax Definition
Syntax Definition
 
String variable in php
String variable in phpString variable in php
String variable in php
 
Pure and Declarative Syntax Definition: Paradise Lost and Regained
Pure and Declarative Syntax Definition: Paradise Lost and RegainedPure and Declarative Syntax Definition: Paradise Lost and Regained
Pure and Declarative Syntax Definition: Paradise Lost and Regained
 
Formal Grammars
Formal GrammarsFormal Grammars
Formal Grammars
 
Processing Regex Python
Processing Regex PythonProcessing Regex Python
Processing Regex Python
 
python Function
python Function python Function
python Function
 
Term Rewriting
Term RewritingTerm Rewriting
Term Rewriting
 
Compiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint ResolutionCompiler Construction | Lecture 9 | Constraint Resolution
Compiler Construction | Lecture 9 | Constraint Resolution
 

Similar a Perl6 signatures

Similar a Perl6 signatures (20)

ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Go Java, Go!
Go Java, Go!Go Java, Go!
Go Java, Go!
 
Practical approach to perl day2
Practical approach to perl day2Practical approach to perl day2
Practical approach to perl day2
 
Apache pig
Apache pigApache pig
Apache pig
 
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
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)Idiomatic Javascript (ES5 to ES2015+)
Idiomatic Javascript (ES5 to ES2015+)
 
Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)
 
Hadoop Pig
Hadoop PigHadoop Pig
Hadoop Pig
 
Es6 to es5
Es6 to es5Es6 to es5
Es6 to es5
 
An Intro To ES6
An Intro To ES6An Intro To ES6
An Intro To ES6
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
OSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP hatersOSDC.TW - Gutscript for PHP haters
OSDC.TW - Gutscript for PHP haters
 
Subroutines
SubroutinesSubroutines
Subroutines
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
Haskell Jumpstart
Haskell JumpstartHaskell Jumpstart
Haskell Jumpstart
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 

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

JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 

Último (20)

JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

Perl6 signatures

  • 1. Perl6 Signatures Everything you didn’t realise you wanted to know, and a whole lot more!
  • 2. 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
  • 3. 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.
  • 4. 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 : eg. outer scope, state declarations
  • 5. Empty Signature (methods) method foo() { say self.bar; } ● Methods with an empty signature also error if called with arguments. ● Have access to self (and the $ alias) though.
  • 6. 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
  • 7. 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
  • 8. Positional Arguments : Defaults and optional sub foo($a,$b?,$c = 5) { say “$a : $b : $c”; } foo(1,2) 1 : 2 : 5 ● Any positions not filled will get their defaults ● Mark an argument as optional with ? after the name.
  • 9. 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.
  • 10. 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}]
  • 11. 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}]
  • 12. 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}]
  • 13. 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)]
  • 14. 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.
  • 15. 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
  • 16. 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.
  • 17. 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 }
  • 18. Bonus Slide : Types sub num-in-country(:$num, :$ccode){...} sub num-in-country(UInt :$num, Str :$ccode){...} sub num-in-country(UInt :$num, Str :$ccode where * ~~ /^ <[a..z]> ** 2 $/ ){...} subset CCode of Str where * ~~ /^ <[a..z]> ** 2 $/; sub num-in-country(UInt :$num, CCode :$ccode){...} Sub coerced-type( Str() $a ) { say “$a could have been many...” }
  • 19. Bonus Slide : Multi Call subset Seven of Int where * == 7; multi sub foo() { 'No args' } multi sub foo(5) { 'Called with 5' } multi sub foo(Seven $) { 'Called with 7' } multi sub foo( *@a ) { '*@a' } multi sub foo( $a ) { '$a' } multi sub foo( Cool $b ) { 'Cool $b' } multi sub foo( Int $b ) { 'Int $b' } multi sub foo( Int $b where * > 0 ) { 'Int $b where * > 0' }