Rules / Types, classes & roles / basic

Sub Reference

Subroutine

What it is #

Examples, run three ways #

Every example below comes from the official documentation, together with the output that documentation asserts. Each was then executed by Rakudo and by Raku++ when this page was built. Where the three agree, one result is shown; where they do not, all three are — because which of them is wrong is exactly the information worth having.

1 all-differ · 2 no-output · 1 not-runnable · 1 ok · 2 rakupp-differs

class Sub is Routine { }

Not executed: the documentation states no expected output for this example.

sub Int(Str $s){'what?'};
say [Int, Int('42'),&Int('42')];
# OUTPUT: «[(Int) 42 what?]␤»
Documentation
[(Int) 42 what?]
Rakudo
[(Int) 42 what?]
Raku++
[(Int) what? what?]

Raku++ disagrees with both the documentation and Rakudo — a defect.

sub can-be-seener( $whatever ) {
  my sub can-be-seen ( $objection ) {
    return $whatever but $objection;
  }
  return &can-be-seen
}

Not executed: the documentation states no expected output for this example.

my $objectioner = can-be-seener( "Really?");
say $objectioner(42).Int; # OUTPUT: «42␤»

Neither engine can run this in isolation — the example depends on context from the surrounding text.

say 'start';
multi trait_mod:<is>(Sub $s, :$foo){
    say "⟨is foo⟩ has been called with ⟨$foo⟩ on {$s.WHICH}";
}
sub bar() is foo<oi‽> {
    say 'bar has been called'
}
bar();
# OUTPUT: «⟨is foo⟩ has been called with ⟨oi‽⟩ on Sub|47563000␤start␤bar has been called␤»
Documentation
⟨is foo⟩ has been called with ⟨oi‽⟩ on Sub|47563000
start
bar has been called
Rakudo
⟨is foo⟩ has been called with ⟨oi‽⟩ on Sub|3725355590928
start
bar has been called
Raku++
start
⟨is foo⟩ has been called with ⟨$foo⟩ on Sub|&bar
bar has been called

All three differ. Needs a human.

Not yet examined. Which of these is correct has not been established — do not treat either engine as settled here.

multi trait_mod:<is>(Variable $a, :@foo [$firstpos, *@restpos, :$named, *%restnameds]) {
    say [$firstpos, @restpos, $named, %restnameds]
}
my $x is foo[1,2,3,:named<a>, :2b, :3c] = 1
# OUTPUT: «[1 [2 3] a {b => 2, c => 3}]␤»
Documentation
[1 [2 3] a {b => 2, c => 3}]
Rakudo
[1 [2 3] a {b => 2, c => 3}]
Raku++

Raku++ disagrees with both the documentation and Rakudo — a defect.

multi trait_mod:<is> (Sub $s, :$foo) is foo {
    say 'is foo called'
}
sub bar {}
&trait_mod:<is>(&bar, :foo);
# OUTPUT: «is foo called␤is foo called␤»
Output
is foo called
is foo called

Documentation, Rakudo and Raku++ all agree.