Passing functions as arguments
Functions in Perl 6 can be passed to other functions as arguments. A typical example is a sort algorithm that needs a function to compare two values. Depending on the data types, it can be different functions that know how to compare the values of that type.
Let's examine the following tiny example:
sub less($a, $b) {$a < $b} sub more($a, $b) {$a > $b} sub compare($a, $b, $f) { $f($a, $b) } say compare(10, 20, &less); # True say compare(10, 20, &more); # False
The main code calls the compare
sub with three arguments—two integer numbers and a reference to one of the functions—&less
or &more
. An ampersand before the name tells us that a function should not be called at this point (remember that, in Perl 6, parentheses are not required when calling a function).
Inside the compare
function, the third argument $f
is a reference to a function. You can now call the referenced function by appending a list of arguments—$f($a, $b)
. This will...