Collecting data with gather and take
Preparing data lists can be very expressively organized with a pair of keywords in Perl 6—gather
and take
. The easiest way to understand how that works is by taking a look at the following example:
my @data = gather { take 'a'; take 'b'; } say @data;
The block of code after the gather
keyword returns a sequence that is saved in the @data
array. The elements of the sequence are provided by the take
keywords. So, there will be two elements in @data
, as you can see here:
[a b]
Let's consider a bigger example. It contains a two-dimensional matrix of integer numbers and a list of instructions. The instructions are the four directions—left
, right
, up
, and down
, and a command— take-it
. You should start at the center of the matrix, then move the current position according to the instructions, and pick up numbers if the instruction tells you to.
my @matrix = ( [ 8, 10, 3, 16, 11], [ 4, 13, 5, 1, 6], [20, 9, 0, 15, 19], [14, 2, 24, 7, 23], ...