๐Ÿ“˜ Passing arrays to subroutines in Perl 6

Pass data, contained in an array, to a subroutine.

In Perl 6, an array can be passed to a subroutine as easily as a scalar. You simply define it in a signature and pass it together with other arguments.

my @colours = <red green blue>;

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

f(@colours, ', '); # Prints: red, green, blue

Theย @colours array is passed to theย f sub, and it lands in theย @data variable inside the sub. An additional second argument,ย $sep, receives its own data.

In cases when a sub expects separate scalars, and youโ€™ve got your data in an array, flattening it helps:

sub g($a, $b, $c, $sep) {
    say "$a$sep$b$sep$c";
}
g(|@colours, ', '); # Prints: red, green, blue

In the sub call, an array name is prefixed with a vertical bar, and the compiler, therefore, knows that you are not passing an array as a whole but that you are using its elements as values to be assigned to the scalar argumentsย $a,ย $b, andย $c.

The number of elements in the array has to match with the number of corresponding subroutine arguments, otherwise one of the following errors occurs:ย Too few positionals passed or Too many positionals passed.

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