Control flow

gather / take

Full

Build a lazy list by taking values from anywhere inside a block.

gather runs a block and collects every value handed to take inside it — however deeply nested — into a single lazy list. It decouples producing values from the loop or logic that decides which to emit.

gather over a loop #

my @evens = gather for 1..10 { take $_ if $_ %% 2 }
say @evens;
Output
[2 4 6 8 10]

Only the numbers that reach a take end up in the list — the if filters inline.

take from nested code #

take can appear anywhere the gather block reaches, including inside called blocks, so production logic can be spread out.

my @out = gather {
    take "start";
    take $_ for <a b>;
    take "end";
}
say @out;
Output
[start a b end]

Notes #