Camelia
Prev: Optional parameters

Named only parameters

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

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!

tutorial/subroutines/required_params_named.p6

#!/usr/bin/env 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


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:
Email:
Full name:
This is a newsletter temporarily running on my personal site (szabgab.com) using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2012-01-01


Prev: Optional parameters

Comments

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.8310563

Perl 6 Tricks and Treats newsletter

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