Kavorka::Manual::Functions - fun keyword
Kavorka provides the fun keyword for the purpose of defining functions (as against methods, etc).
fun
The anatomy of a function:
The keyword introducing the function.
The function name (optional).
The signature (optional).
Traits (optional).
The prototype (optional).
The attribute list (optional).
The function body.
Example:
# (1) (2) (3) (4) (5) (6) (7) fun foobar ($foo, $bar) is cool :($$) :cached { return $foo + $bar } # (1) (6) my $f = fun { return $_[0] + $_[1] };
This requires very little explanation. If you're no fun, and don't like the name fun, you can export it with a different name:
use Kavorka fun => { -as => 'function' };
If present, it specifies the name of the function being defined. If no name is present, the declaration is an expression that evaluates to a reference to the function in question.
Functions are automatically forward-declared; a la
sub foobar ($$);
but are installed into the symbol table at run-time. So this works:
if ($ENV{DEBUG}) { fun foobar { ... } } else { fun foobar { ... } }
It is possible to install the function at compile time using the begin trait:
begin
fun foobar but begin { ... }
It is possible to define lexical functions using a lexical variable for a function name:
fun my $add ($x, $y) { $x + $y; } my $sum = $add->(20, 22);
See Kavorka::Manual::Signatures.
See Kavorka::Manual::ExtendingKavorka.
See Kavorka::Manual::PrototypeAndAttributes.
Attributes may alternatively be provided before the signature.
This is more or less what you'd expect from the function body you'd write with sub, however the lexical variables for parameters are pre-declared and pre-populated.
f
func
function
These are all aliases for fun, though not exported by default.
use v5.14; use Kavorka qw( function f ); function make_plusser (Num $x = 1) { return f(Num $y) { $x + $y }; } my $plusser = make_plusser(); say $plusser->(41); # says 42
Please report any bugs to http://rt.cpan.org/Dist/Display.html?Queue=Kavorka.
Kavorka::Manual, Kavorka::Manual::Signatures, Kavorka::Manual::PrototypeAndAttributes, Kavorka::Manual::MultiSubs.
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2013-2014, 2017 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
To install Kavorka, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Kavorka
CPAN shell
perl -MCPAN -e shell install Kavorka
For more information on module installation, please visit the detailed CPAN module installation guide.