Camelia
Prev: Subroutines in Perl 6

Simple definition with required parameters

In order do define a subroutine in Perl 6 we use the "sub" keyword. Then comes the name of the subroutine with a list of parameters. After that comes a block that implements the subroutin where you can use the variables defined in the signature.

In the most simple case shown in the example we have two scalar variables ($a and $b) as parameters. In this case the parameters are required. The user of the sub has to supply them though there are several way to do that.

The simple way is just to provide the in the same order as they are shown in the signature.

The most basic example I usually show is the add function with two parameters. That's usually enough in Perl 5 but very far from that in Perl 6.

Positional parameters:

examples/subroutines/required_params.p6
#!/usr/bin/env perl6
use v6;

sub add ($a, $b) {
    return $a + $b;
}

say add(2, 3);      # returns 5

#say add(2);        # is an error
#say add(2, 3, 4);  # is an error

Then if you try to call this with 3 parameters like this:

 say add(2, 3, 4);

Rakudo will throw a run-time exception as it cannot find the appropriate function.


Prev: Subroutines in Perl 6

Table of Contents

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: