Documentation for syntax sub
assembled from the following pages:
Language documentation: Functions §
From Functions
(Functions) Syntax sub sub §
The basic way to create a subroutine is to use the sub
declarator followed by an optional identifier:
sub my-func my-func;
The sub declarator returns a value of type Sub that can be stored in any container:
my = sub c; # 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 function say 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»