syntax sub

Documentation for syntax sub assembled from the following types:

language documentation Functions

From Functions

(Functions) declarator sub sub

The basic way to create a subroutine is to use the sub declarator followed by an optional identifier:

sub my-func { say "Look ma, no args!" }
my-func;

The sub declarator returns a value of type Sub that can be stored in any container:

my &c = sub { say "Look ma, no name!" }
c;     # OUTPUT: «Look ma, no name!␤» 
 
my Any:D $f = sub { say 'Still nameless...' }
$f();  # OUTPUT: «Still nameless...␤» 
 
my Code \a = sub { say raw containers don't implement postcircumfix:<( )> };
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{ say 'oi‽' };
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 ($phrase) {
    say $phrase ~ "!!!!"
}
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($str{
    # Puts a slash before non-alphanumeric characters 
    S:g[<-alpha -digit>] = "\\$/" given $str
}
 
say escape 'foo#bar?'# OUTPUT: «foo\#bar\?␤» 
 
{
    sub escape($str{
        # Writes each non-alphanumeric character in its hexadecimal escape 
        S:g[<-alpha -digit>] = "\\x[{ $/.ord.base(16}]" given $str
    }
 
    say escape 'foo#bar?' # OUTPUT: «foo\x[23]bar\x[3F]␤» 
}
 
# 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 ($a$b{ $a ** 2 + $b ** 2 }(34# 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 -> $a$b { $a ** 2 + $b ** 2 }(34)    # OUTPUT: «25␤»

Or even

say { $^a ** 2 + $^b ** 2 }(34)            # OUTPUT: «25␤»