📘 Plural endings using Perl 6

Put a noun in the correct form—singular or plural—depending on the number next to it.

In program outputs, it is often required to print some number followed by a noun, for example:

10 files copied

If there is only one file, then the phrase should be ‘1 file copied’ instead. Let’s see how Perl 6 can help.

Of course, it is quite easy to print a noun separately using string concatenation to make the whole phrase:

for 1, 2, 3 -> $n {                     # Program output:
    my $word = 'file';                  # 1 file found
    $word ~= 's' if $n > 1;             # 2 files found
    say "$n $word found";               # 3 files found
}

It is also a good practice to interpolate the word choice into the string itself to avoid additional lines of code and to get rid of temporary variables.

The following program generates the same output:

for 1, 2, 3 -> $n {
    say "$n file{'s' if $n > 1} found";
}

A code block in curly braces inside the string contains a regular Perl 6 code. It returns 's' if the number $n is greater than one. Notice that there is no need to use a ternary operator here; a postfix if looks very self-explaining.

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