Prev: Subroutines in Perl 6

Simple definition with required parameters

Note! This site is about Perl 6.
If you are looking for a solution for Perl 5, please check out the Perl 5 tutorial.

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:


#!/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.

The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Full name:
This is a newsletter temporarily running on my personal site ( using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2012-01-01

Prev: Subroutines in Perl 6


In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 3.58714995

Perl 6 Tricks and Treats newsletter

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