September 2017
Beginner
402 pages
9h 52m
English
The great part of Perl 6 is that it allows passing arrays and hashes in function signatures, Meaning that an array is passed as a single value, not as a list of its values. Consider the following simple example of how the add function can be modified to return the sum of all the elements of an array:
sub add(@arr) {
[+] @arr
}
my @a = <10 20 30>;
say add(@a); # 60
The [+] construction is a reduced form of the + operator; see the details in Chapter 4, Working with Operators. It returns the sum of all the elements of the @arr array, which is the only argument of the sub.
You may safely add more arguments after the array to the sub. Let's create a function to calculate the sum of the first $n elements of an array:
sub sum_first(@a, ...