Mostly Harmless Docs/Subroutines

Copy/paste this into your editor; save, and run.

#!/usr/bin/env perl6

# Create a sub that takes no args.
sub foo {
    say 'Hi from foo.';
}

# Call it.
foo;
foo();
say '-' x 42;

# Create a sub that takes 3 positional args.
sub bar($a, $b, $c) {
    say 'Hello from bar.';
    say "\$a: $a.";
    say "\$b: $b.";
    say "\$c: $c.";
}

bar(1, 2, 'something');
say '-' x 42;

# Create a sub that has you call it via named args.
sub baz(:$a, :$b) {
    say 'Aloha from baz.';
    say "\$a: $a";
    say "\$b: $b";
}

baz(a => 11, b => 12);
baz(:a(11), :b(12));    # same
baz(:b(12), :a(11));    # same
# baz(11, 12);          # Error.
say '-' x 42;

# Note, you can't call `bar()` with named args.
# bar(:a(1), :b(2), :c(3));  # Error.

# Create a sub that can modify an outside variable.
my $i = 1;
sub moo($j is rw) {
    say 'Howdy from moo.';
    $j = 3;
    say "I changed it to $j.";
}

moo $i;  # 3, of course
say $i;  # 3
say '-' x 42;

# Passing in an array works like you'd expect.
sub qux(@a) {
    say 'Hallo from qux. You passed:';
    .say for @a;
}

my @ar = 1 .. 5;
qux @ar;
say '-' x 42;

# Returning an array also does what's expected.
sub quux {
    say 'Checking in from quux.';
    return 1, 2, 3;
}

my ($x, $y, $z) = quux;
say "\$x = $x";
say "\$y = $y";
say "\$z = $z";
say '-' x 42;

Subs can also “slurp” up extra positional or named args you pass them:

#!/usr/bin/env perl6

sub foo1($a, $b, *@rest) {
    say "\$a: $a";
    say "\$b: $b";
    say "the rest: {@rest}";
}

foo1(1, 2, 3, 4, 5);
#=>
# $a: 1
# $b: 2
# the rest: 3 4 5

#-----------------------------------------
sub foo2(:$a, :$b, *%rest) {
    say "\$a: $a";
    say "\$b: $b";
    say "the rest: {%rest}";
}

foo2(:a(1), :b(2), :c(3), :d(4), :e(5));
#=>
# $a: 1
# $b: 2
# the rest: c     3 d     4 e     5

Main | Next: Exceptions