SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
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' }

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie Perl6 signatures

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Kürzlich hochgeladen (20)

Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

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' }