Course of Raku / Essentials / Functions essentials / Creating and calling functions
Default values
Both positional and named parameters can have default values. If the function has a default value for the given parameter, that parameter may be skipped when calling the function.
Positional parameters
An example of a default value for a function with positional parameters:
sub greet($name = 'World') {
say "Hello, $name!";
}
greet('Merinda');
greet();The first call uses the name passed as the only argument and thus
prints Hello, Merinda!. The second call uses the default
value and prints Hello, World!.
If a function has more than one parameter, then the default values can only be used at the end of the list of them:
sub f($a, $b, $c = 42, $d = 50) { . . . } # correct
# sub f($a = 10, $b = 20, $c, $d) { . . . } # WRONGNamed parameters
The same syntax is used for setting default values for named parameters:
sub greet(:$name = 'World') {
say "Hello, $name!";
}
greet(name => 'Merinda'); # Hello, Merinda!
greet(); # Hello, World!The order of the named parameters does not matter, so any of them can have default values, even the first in the list:
sub greet(:$greeting = 'Hello', :$name) {
say "$greeting, $name!";
}
greet(name => 'Alla'); # Hello, Alla!Practice
Complete the quizzes that cover the contents of this topic.
Course navigation
← Quiz 2 — Variables as named parameters | Quiz — Defining default values →
💪 Or jump directly to the exercises in this
section.
Translations of this page: English • Deutsch • Español • Italiano • Latviešu • Nederlands • Български • Русский • Українська