lazy (statement prefix) lazy

Documentation for lazy (statement prefix) lazy assembled from the following types:

language documentation Statement prefixes

From Statement prefixes

(Statement prefixes) lazy (statement prefix) lazy

As a statement prefix, lazy acts in front of any statement, including for loops, saving the execution for when the variable they are assigned to is actually needed.

my $incremented = 0;
my $var = lazy for <1 2 3 4> -> $d {
say $incremented# OUTPUT: «0␤» 
say eager $var;   # OUTPUT: «(0 1 2 3)␤» 
say $incremented# OUTPUT: «4␤» 

The $incremented variable is only incremented, that is, the internal part of the loop is only run when we eagerly evaluate the variable $var that contains the lazy loop. Eagerness can be applied on a variable in other ways, such as calling the .eager method on it.

my @array = lazy { (^3).map*² )  };
say @array;       # OUTPUT: «[...]» 
say @array.eager# OUTPUT: «[0 1 4]␤» 

This prefix can also be used in front of gather to make the inner statements behave lazily; in general, any set of statements that returns a value will be made lazy using this.