Named only parameters


The user can decide to pass the parameters in as key-value pairs.

Parameters that are declared as positional can always passed as named but if the variable name is prefixed with a colon : then it can only be passed as a named argument and it is optional. To make a named-only parameter required put an exclamation mark ! after it: :$b!

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

sub foo($a, :$b) {
    return $a + $b * 2;
}

say foo(b => 2, 3);   # 7
#say foo(4, 9);        # Too many positional parameters passed; got 2 but expected 1

say foo(2);           # 2   Use of uninitialized value in numeric context
#say foo(2, 3, 4);    # Too many positional parameters passed; got 3 but expected 1

Copyright 2006, 2007, 2008, 2009, 2010 Gabor Szabo http://szabgab.com/ Index | TOC
If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed