๐Ÿ“˜ Subroutines, or subs in Perl 6

๐Ÿ“˜ Subroutines, or subs in Raku

N. B. Perl 6 has been renamed to Raku. Click to read more.

For a sub, which takes no arguments, its definition and the call are very straightforward and easy.

sub call-me {
ย ย ย  say "I'm called"


The syntax for declaring a subโ€™s parameters is similar to what other languages (including Perl 5.20 and higher) provide.

sub cube($x) {
ย ย ย  return $x ** 3;

say cube(3); # 27

The required parameters are a comma-separated list in the parentheses immediately after the sub name. No other keywords, such as my, are required to declare them.

sub min($x, $y) {
ย ย ย  return $x < $y ?? $x !! $y;

say min(-2, 2);ย  # -2
say min(42, 24); # 24

(?? … !! is a ternary operator in Perl 6. Also, thereโ€™s a built-in operator min; see the details in the Chapter 2.)

The above-declared arguments are required; thus, if a sub is called with a different number of actual arguments, an error will occur.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code