Our next program in this chapter is a simple loop that prints the numbers from 10 to 15 and calculates their sum. Let us first print in numbers. As we've seen in Chapter 5, Control Flow, there are different ways of making a loop in Perl 6. Choosing between them can lead us already in the direction of functional programming.
The loop cycle needs a loop counter:
my $sum = 0;
loop (my $n = 10; $n <= 15; $n++) {
$sum += $n;
}
say $sum; # 75
There are two variables that change their values in this program—$n and $sum. It is very easy to get rid of the $n counter, and thus re-assigning it a value:
my $sum = 0;
for 10..15 {
$sum += $_;
}
say $sum;
Now, we are using the $_ variable instead of $n and actually the for loop can use an explicit loop variable:
my $sum = 0;
for 10..15 -> $n {
$sum += $n;
}
say $sum;
The difference between this code and the...