In Functions§
See primary documentation in context for Subroutines
The basic way to create a subroutine is to use the sub
declarator followed by an optional identifier:
sub my-funcmy-func;
The sub declarator returns a value of type Sub
that can be stored in any container:
my = subc; # OUTPUT: «Look ma, no name!»my Any = sub(); # OUTPUT: «Still nameless...»my Code \a = sub ;a.(); # OUTPUT: «raw containers don't implement postcircumfix:<( )>»
The declarator sub
will declare a new name in the current scope at compile time. As such, any indirection has to be resolved at compile time:
constant aname = 'foo';sub ::(aname) ;foo;
This will become more useful once macros are added to Raku.
To have the subroutine take arguments, a Signature
goes between the subroutine's name and its body, in parentheses:
sub exclaim ()exclaim "Howdy, World";
By default, subroutines are lexically scoped. That is, sub foo {...}
is the same as my sub foo {...}
and is only defined within the current scope.
sub escape()say escape 'foo#bar?'; # OUTPUT: «foo\#bar\?»# Back to original escape functionsay escape 'foo#bar?'; # OUTPUT: «foo\#bar\?»
Subroutines don't have to be named. If unnamed, they're called anonymous subroutines.
say sub (, ) (3, 4) # OUTPUT: «25»
But in this case, it's often desirable to use the more succinct Block
syntax. Subroutines and blocks can be called in place, as in the example above.
say -> , (3, 4) # OUTPUT: «25»
Or even
say (3, 4) # OUTPUT: «25»