🔬51. Colonpair in Perl 6’s Grammar, part 2

Today, we continue examining the colonpair syntax in Perl 6 and will give an addition to the third branch of the token. Here’s the branch we are looking at today:

#  branch 3
| <identifier>
    { $*key := $<identifier>.Str; }
    [
    || <.unsp>? :dba('pair value') <coloncircumfix($*key)> { $*value := $<coloncircumfix>; }
    || { $*value := 1; }
    ]

It contains two alternative paths. If you don’t specify the value, it is set to 1:

sub h(:$value) {
    say $value;
}

h(:value); # True

This is handled by the second alternative in this branch:

|| { $*value := 1; }

But you also may match the first one:

|| <.unsp>? :dba('pair value') <coloncircumfix($*key)> {
    $*value := $<coloncircumfix>;
}

(The unsp is the so-called unspace — an optional space prefixed by the backslash if you want to have some whitespace before the parenthesesis.)

The coloncircumfix token basically allows us to use paired brackets (actually, those defined by circumfix) to enclose the value. This is how it is defined:

token coloncircumfix($front) {
    # reset $*IN_DECL in case this colonpair is part of var we're
    # declaring, since colonpair might have other vars. Don't make those
    # think we're declaring them
    :my $*IN_DECL := '';
    [
    | '<>' <.worry("Pair with <> really means an empty list, not null string; use :$front" ~ "('') to represent the null string,\n or :$front" ~ "() to represent the empty list more accurately")>
    | {} <circumfix>
    ]
}

The following code is using this option:

h(:value<10>); # 10
h(:value(11)); # 11
h(:value[12]); # 12

You can’t pass an empty string using empty brackets like h(:value<>):

Potential difficulties:
  Pair with <> really means an empty list, not null string;
  use :value('') to represent the null string,
  or :value() to represent the empty list more accurately

 

One thought on “🔬51. Colonpair in Perl 6’s Grammar, part 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s