πŸ“˜ Variadic parameters in a sub in Perl 6

Pass a few scalars to a sub and work with them as with an array inside the sub.

The task is to take a few scalar parameters and pass them to a single array in the subroutine. 

Here is an example of how to do that, prefixing an array name with a star:

sub h($sep, *@data) {
    @data.join($sep).say;
}

h(', ', 'red', 'green', 'blue');

In Perl 6, theΒ *@data is called aΒ slurpy parameter. It is an array that consumes all of the arguments passed to the function after theΒ $sep argument. In the example above, three string values are passed. It is also possible to pass any other number of arguments:

h(', ', 'apple');

h(', ', 1, 2, 3, 4, 5);

Or even as a range of values, all of which land in the @data array.

h(', ', 'a' .. 'z');

It is important that in comparison to the solutions from Task 65,Β Passing arrays to subroutines, theΒ $sep argument is mentioned first in the sub signature. If you put it at the end, the compiler refuses to accept that and complains:

Cannot put required parameter $sep after variadic parameters

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