Provides two new keywords, "func" and "method", so that you can write subroutines with signatures instead
of having to spell out "my $self = shift; my($thing) = @_"
"func" is like "sub" but takes a signature where the prototype would normally go. This takes the place
of "my($foo, $bar) = @_" and does a whole lot more.
"method" is like "func" but specifically for making methods. It will automatically provide the invocant
as $self (by default). No more "my $self = shift".
Also allows signatures, very similar to Perl 6 signatures.
Also does type checking, understanding all the types that Moose (or Mouse) would understand.
And it does all this with nosourcefilters.
Signaturesyntax
func echo($message) {
print "$message\n";
}
is equivalent to:
sub echo {
my($message) = @_;
print "$message\n";
}
except the original line numbering is preserved and the arguments are checked to make sure they match the
signature.
Similarly
method foo($bar, $baz) {
$self->wibble($bar, $baz);
}
is equivalent to:
sub foo {
my $self = shift;
my($bar, $baz) = @_;
$self->wibble($bar, $baz);
}
again with checks to make sure the arguments passed in match the signature.
The full signature syntax for each parameter is:
Int|Str \:$param! where $SM_EXPR is ro = $AS_EXPR when $SM_EXPR
\_____/ ^^\____/^ \____________/ \___/ \________/ \___________/
| || | | | | | |
Type_/ || | | | | | |
Aliased?___/ | | | | | | |
Named?______/ | | | | | |
Parameter var___/ | | | | |
Required?__________/ | | | |
Parameter constraint(s)_____/ | | |
Parameter trait(s)______________________/ | |
Default value____________________________________/ |
When default value should be applied_________________________/
Every component except the parameter name (with sigil) is optional.
$SM_EXPR is any expression that is valid as the RHS of a smartmatch, or else a raw block of code. See
"Value constraints".
$AS_EXPR is any expression that is valid as the RHS of an assignment operator. See "Defaults".
@_
Other than removing $self, @_ is left intact. You are free to use @_ alongside the arguments provided by
Method::Signatures.
Namedparameters
Parameters can be passed in named, as a hash, using the ":$arg" syntax.
method foo(:$arg) {
...
}
$object->foo( arg => 42 );
Named parameters are optional by default.
Required positional parameters and named parameters can be mixed, but the named params must come last.
method foo( $a, $b, :$c ) # legal
Named parameters are passed in as a hash after all positional arguments.
method display( $text, :$justify = 'left', :$enchef = 0 ) {
...
}
# $text = "Some stuff", $justify = "right", $enchef = 0
$obj->display( "Some stuff", justify => "right" );
You cannot mix optional positional params with named params, as that leads to ambiguities.
method foo( $a, $b?, :$c ) # illegal
# Is this $a = 'c', $b = 42 or $c = 42?
$obj->foo( c => 42 );
Aliasedreferences
A signature of "\@arg" will take an array reference but allow it to be used as @arg inside the method.
@arg is an alias to the original reference. Any changes to @arg will affect the original reference.
package Stuff;
method add_one(\@foo) {
$_++ for @foo;
}
my @bar = (1,2,3);
Stuff->add_one(\@bar); # @bar is now (2,3,4)
This feature requires Data::Alias to be installed.
Invocantparameter
The method invocant (i.e. $self) can be changed as the first parameter on a per-method basis. Put a colon
after it instead of a comma:
method foo($class:) {
$class->bar;
}
method stuff($class: $arg, $another) {
$class->things($arg, $another);
}
"method" has an implied default invocant of $self:, though that is configurable by setting the invocant
parameter on the "use Method::Signatures" line.
"func" has no invocant, as it is intended for creating subs that will not be invoked on an object.
Defaults
Each parameter can be given a default with the "$arg = EXPR" syntax. For example,
method add($this = 23, $that = 42) {
return $this + $that;
}
Almost any expression can be used as a default.
method silly(
$num = 42,
$string = q[Hello, world!],
$hash = { this => 42, that => 23 },
$code = sub { $num + 4 },
@nums = (1,2,3),
)
{
...
}
Normally, defaults will only be used if the argument is not passed in at all. Passing in "undef" will
override the default. That means ...
Class->add(); # $this = 23, $that = 42
Class->add(99); # $this = 99, $that = 42
Class->add(99, undef); # $this = 99, $that = undef
However, you can specify additional conditions under which a default is also to be used, using a trailing
"when". For example:
# Use default if no argument passed
method get_results($how_many = 1) {...}
# Use default if no argument passed OR argument is undef
method get_results($how_many = 1 when undef) {...}
# Use default if no argument passed OR argument is empty string
method get_results($how_many = 1 when "") {...}
# Use default if no argument passed OR argument is zero
method get_results($how_many = 1 when 0) {...}
# Use default if no argument passed OR argument is zero or less
method get_results($how_many = 1 when sub{ $_[0] <= 0 }) {...}
# Use default if no argument passed OR argument is invalid
method get_results($how_many = 1 when sub{ !valid($_[0]) }) {...}
In other words, if you include a "when value" after the default, the default is still used if the
argument is missing, but is also used if the argument is provided but smart-matches the specified value.
Note that the final two examples above use anonymous subroutines to conform their complex tests to the
requirements of the smartmatch operator. Because this is useful, but syntactically clumsy, there is also
a short-cut for this behaviour. If the test after "when" consists of a block, the block is executed as
the defaulting test, with the actual argument value aliased to $_ (just like in a "grep" block). So the
final two examples above could also be written:
# Use default if no argument passed OR argument is zero or less
method get_results($how_many = 1 when {$_ <= 0}) {...}
# Use default if no argument passed OR argument is invalid
method get_results($how_many = 1 when {!valid($_)}) } {...}
The most commonly used form of "when" modifier is almost certainly "when undef":
# Use default if no argument passed OR argument is undef
method get_results($how_many = 1 when undef) {...}
which covers the common case where an uninitialized variable is passed as an argument, or where supplying
an explicit undefined value is intended to indicate: "use the default instead."
This usage is sufficiently common that a short-cut is provided: using the "//=" operator (instead of the
regular assignment operator) to specify the default. Like so:
# Use default if no argument passed OR argument is undef
method get_results($how_many //= 1) {...}
Earlier parameters may be used in later defaults.
method copy_cat($this, $that = $this) {
return $that;
}
Any variable that has a default is considered optional.
TypeConstraints
Parameters can also be given type constraints. If they are, the value passed in will be validated
against the type constraint provided. Types are provided by Any::Moose which will load Mouse if Moose is
not already loaded.
Type constraints can be a type, a role or a class. Each will be checked in turn until one of them
passes.
* First, is the $value of that type declared in Moose (or Mouse)?
* Then, does the $value have that role?
$value->DOES($type);
* Finally, is the $value an object of that class?
$value->isa($type);
The set of default types that are understood can be found in Mouse::Util::TypeConstraints (or
Moose::Util::TypeConstraints; they are generally the same, but there may be small differences).
# avoid "argument isn't numeric" warnings
method add(Int $this = 23, Int $that = 42) {
return $this + $that;
}
Mouse and Moose also understand some parameterized types; see their documentation for more details.
method add(Int $this = 23, Maybe[Int] $that) {
# $this will definitely be defined
# but $that might be undef
return defined $that ? $this + $that : $this;
}
You may also use disjunctions, which means that you are willing to accept a value of either type.
method add(Int $this = 23, Int|ArrayRef[Int] $that) {
# $that could be a single number,
# or a reference to an array of numbers
use List::Util qw<sum>;
my @ints = ($this);
push @ints, ref $that ? @$that : $that;
return sum(@ints);
}
If the value does not validate against the type, a run-time exception is thrown.
# Error will be:
# In call to Class::add : the 'this' parameter ("cow") is not of type Int
Class->add('cow', 'boy'); # make a cowboy!
You cannot declare the type of the invocant.
# this generates a compile-time error
method new(ClassName $class:) {
...
}
ValueConstraints
In addition to a type, each parameter can also be specified with one or more additional constraints,
using the "$arg where CONSTRAINT" syntax.
method set_name($name where qr{\S+ \s+ \S+}x) {
...
}
method set_rank($rank where \%STD_RANKS) {
...
}
method set_age(Int $age where [17..75] ) {
...
}
method set_rating($rating where { $_ >= 0 } where { $_ <= 100 } ) {
...
}
method set_serial_num(Int $snum where {valid_checksum($snum)} ) {
...
}
The "where" keyword must appear immediately after the parameter name and before any trait or default.
Each "where" constraint is smartmatched against the value of the corresponding parameter, and an
exception is thrown if the value does not satisfy the constraint.
Any of the normal smartmatch arguments (numbers, strings, regexes, undefs, hashrefs, arrayrefs, coderefs)
can be used as a constraint.
In addition, the constraint can be specified as a raw block. This block can then refer to the parameter
variable directly by name (as in the definition of "set_serial_num()" above), or else as $_ (as in the
definition of "set_rating()".
Unlike type constraints, value constraints are tested after any default values have been resolved, and in
the same order as they were specified within the signature.
Placeholderparameters
A positional argument can be ignored by using a bare "$" sigil as its name.
method foo( $a, $, $c ) {
...
}
The argument's value doesn't get stored in a variable, but the caller must still supply it. Value and
type constraints can be applied to placeholders.
method bar( Int $ where { $_ < 10 } ) {
...
}
Parametertraits
Each parameter can be assigned a trait with the "$arg is TRAIT" syntax.
method stuff($this is ro) {
...
}
Any unknown trait is ignored.
Most parameters have a default traits of "is rw is copy".
ro Read-only. Assigning or modifying the parameter is an error. This trait requires Const::Fast to be
installed.
rw Read-write. It's ok to read or write the parameter.
This is a default trait.
copy
The parameter will be a copy of the argument (just like "my $arg = shift").
This is a default trait except for the "\@foo" parameter (see "Aliased references").
alias
The parameter will be an alias of the argument. Any changes to the parameter will be reflected in
the caller. This trait requires Data::Alias to be installed.
This is a default trait for the "\@foo" parameter (see "Aliased references").
Mixingvalueconstraints,traits,anddefaults
As explained in "Signature syntax", there is a defined order when including multiple trailing aspects of
a parameter:
• Any value constraint must immediately follow the parameter name.
• Any trait must follow that.
• Any default must come last.
For instance, to have a parameter which has all three aspects:
method echo($message where { length <= 80 } is ro = "what?") {
return $message
}
Think of "$message where { length <= 80 }" as being the left-hand side of the trait, and "$message where
{ length <= 80 } is ro" as being the left-hand side of the default assignment.
Slurpyparameters
A "slurpy" parameter is a list or hash parameter that "slurps up" all remaining arguments. Since any
following parameters can't receive values, there can be only one slurpy parameter.
Slurpy parameters must come at the end of the signature and they must be positional.
Slurpy parameters are optional by default.
The"yadayada"marker
The restriction that slurpy parameters must be positional, and must appear at the end of the signature,
means that they cannot be used in conjunction with named parameters.
This is frustrating, because there are many situations (in particular: during object initialization, or
when creating a callback) where it is extremely handy to be able to ignore extra named arguments that
don't correspond to any named parameter.
While it would be theoretically possible to allow a slurpy parameter to come after named parameters, the
current implementation does not support this (see "Slurpy parameter restrictions").
Instead, there is a special syntax (colloquially known as the "yada yada") that tells a method or
function to simply ignore any extra arguments that are passed to it:
# Expect name, age, gender, and simply ignore anything else
method BUILD (:$name, :$age, :$gender, ...) {
$self->{name} = uc $name;
$self->{age} = min($age, 18);
$self->{gender} = $gender // 'unspecified';
}
# Traverse tree with node-printing callback
# (Callback only interested in nodes, ignores any other args passed to it)
$tree->traverse( func($node, ...) { $node->print } );
The "..." may appear as a separate "pseudo-parameter" anywhere in the signature, but is normally placed
at the very end. It has no other effect except to disable the usual "die if extra arguments" test that
the module sets up within each method or function.
This means that a "yada yada" can also be used to ignore positional arguments (as the second example
above indicates). So, instead of:
method verify ($min, $max, @etc) {
return $min <= $self->{val} && $self->{val} <= $max;
}
you can just write:
method verify ($min, $max, ...) {
return $min <= $self->{val} && $self->{val} <= $max;
}
This is also marginally more efficient, as it does not have to allocate, initialize, or deallocate the
unused slurpy parameter @etc.
The bare "@" sigil is a synonym for "...". A bare "%" sigil is also a synonym for "...", but requires
that there must be an even number of extra arguments, such as would be assigned to a hash.
Requiredandoptionalparameters
Parameters declared using "$arg!" are explicitly required. Parameters declared using "$arg?" are
explicitly optional. These declarations override all other considerations.
A parameter is implicitly optional if it is a named parameter, has a default, or is slurpy. All other
parameters are implicitly required.
# $greeting is optional because it is named
method hello(:$greeting) { ... }
# $greeting is required because it is positional
method hello($greeting) { ... }
# $greeting is optional because it has a default
method hello($greeting = "Gruezi") { ... }
# $greeting is required because it is explicitly declared using !
method hello(:$greeting!) { ... }
# $greeting is required, even with the default, because it is
# explicitly declared using !
method hello(:$greeting! = "Gruezi") { ... }
The@_signature
The @_ signature is a special case which only shifts $self. It leaves the rest of @_ alone. This way
you can get $self but do the rest of the argument handling manually.
Note that a signature of "(@_)" is exactly equivalent to a signature of "(...)". See "The yada yada
marker".
Theemptysignature
If a method is given the signature of "()" or no signature at all, it takes no arguments.
AnonymousMethods
An anonymous method can be declared just like an anonymous sub.
my $method = method ($arg) {
return $self->foo($arg);
};
$obj->$method(42);
Options
Method::Signatures takes some options at `use` time of the form
use Method::Signatures { option => "value", ... };
invocant
In some cases it is desirable for the invocant to be named something other than $self, and specifying it
in the signature of every method is tedious and prone to human-error. When this option is set, methods
that do not specify the invocant variable in their signatures will use the given variable name.
use Method::Signatures { invocant => '$app' };
method main { $app->config; $app->run; $app->cleanup; }
Note that the leading sigil must be provided, and the value must be a single token that would be valid as
a perl variable. Currently only scalar invocant variables are supported (eg, the sigil must be a "$").
This option only affects the packages in which it is used. All others will continue to use $self as the
default invocant variable.
compile_at_BEGIN
By default, named methods and funcs are evaluated at compile time, as if they were in a BEGIN block, just
like normal Perl named subs. That means this will work:
echo("something");
# This function is compiled first
func echo($msg) { print $msg }
You can turn this off lexically by setting compile_at_BEGIN to a false value.
use Method::Signatures { compile_at_BEGIN => 0 };
compile_at_BEGIN currently causes some issues when used with Perl 5.8. See "Earlier Perl versions".
debug
When true, turns on debugging messages about compiling methods and funcs. See DEBUGGING. The flag is
currently global, but this may change.
DifferencesfromPerl6
Method::Signatures is mostly a straight subset of Perl 6 signatures. The important differences...
Restrictionsonnamedparameters
As noted above, there are more restrictions on named parameters than in Perl 6.
Namedparametersarejusthashes
Perl 5 lacks all the fancy named parameter syntax for the caller.
Parametersarecopies.
In Perl 6, parameters are aliases. This makes sense in Perl 6 because Perl 6 is an "everything is an
object" language. Perl 5 is not, so parameters are much more naturally passed as copies.
You can alias using the "alias" trait.
Can'tusepositionalparamsasnamedparams
Perl 6 allows you to use any parameter as a named parameter. Perl 5 lacks the named parameter
disambiguating syntax so it is not allowed.
Additionofthe"\@foo"referencealiasprototype
In Perl 6, arrays and hashes don't get flattened, and their referencing syntax is much improved. Perl 5
has no such luxury, so Method::Signatures added a way to alias references to normal variables to make
them easier to work with.
Additionofthe@_prototype
Method::Signatures lets you punt and use @_ like in regular Perl 5.