๐Ÿ“˜ Subroutines, or subs in Perl 6

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s