Named parameters: Difference between revisions

m
Section belongs in positional parameters
(Added information about Perl 5.20's experimental signatures)
m (Section belongs in positional parameters)
Line 792:
Verbosity specified as 3.
Safe mode off.</pre>
 
 
----
 
 
Introduced '''experimentally''' in 5.20.0, subroutines can have signatures when the feature is turned on:
<lang perl>use 5.020;
use experimental 'signatures';</lang>
Perl policy states that all bets are off with experimental features—their behavior is subject to change at any time, and they may even be removed completely (''this feature will most likely stay in, but expect changes in the future that will break any scripts written using it as it stands in 5.20.1'').
 
A simple example of a function with an arity of exactly two:
<lang perl>sub add ($x, $y) {
return $x + $y;
}
add(4, 6); # 10</lang>
 
This can be made more flexible with default parameters:
<lang perl>sub add_defaults ($x = 0, $y = return $x) {
return $x + $y
}
add_defaults(1); # 1
add_defaults(1, 2); # 3</lang>
 
"Slurpy" parameters can also be specified, which take 0 or more parameters.
<lang perl>sub add_many ($x, @rest) {
$x += $_ foreach @rest;
return $x;
}
add_many(1, 2, 3, 4, 5); # 15</lang>
 
To discard extra parameters and keep a function variadic, Perl allows the syntax of a bare sigil to indicate a discarded argument:<lang Perl>sub omit_param ($one, $, $three) {
print "One: $one, Two: n/a, Three: $three\n";
}
omit_param(1, 2, 3); # One: 1, Two: n/a, Three: 3</lang>
This can also be used to simulate a function that has a default interface:<lang Perl>sub foo ($x, $y = 0) {
return $x + $y;
}
sub foo_null ($, $ =) {
return;
}</lang>
 
You can even assign default values based on other parameters (or from function calls, expressions, et cetera):
<lang Perl>sub clone_param ($x, $y = $x) { ... }</lang>
In any scope that subroutine signatures is active, subroutines '''cannot''' have prototypes in the sub (PROTO) { ... } form; they must be declared as an attribute:<lang Perl>sub current_syntax :prototype(PROTO) (ARGS) { ... }</lang>While attributes must precede signatures as of 5.20.1, the following syntax has been proposed for future versions:<lang Perl>sub not_implemented_yet (ARGS) :prototype(PROTO) { ... }</lang>
The truly insane can even call a goto in an argument's default assignment (but please don't).
 
=={{header|Perl 6}}==
Anonymous user