Loops repeat a block of code for each value in a range.

for loop A `for` loop can visit each number in a range like `1..$limit`.

Loops

limit
loops.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $limit = 4;
my $total = 0;

for my $number (1..$limit) {
    $total += $number;
}

print "limit=$limit\n";
print "total=$total\n";
use strict;
use warnings;

my $limit = 2;
my $total = 0;

for my $number (1..$limit) {
    $total += $number;
}

print "limit=$limit\n";
print "total=$total\n";
use strict;
use warnings;

my $limit = 6;
my $total = 0;

for my $number (1..$limit) {
    $total += $number;
}

print "limit=$limit\n";
print "total=$total\n";
  1. $limit ← 4, $total ← 0

    4my $limit→ 4 = 4; #@limit=2, 65my $total→ 0 = 0;
  2. $total ← 1

    pass 1 of 4
    7for my $number1 (1..$limit4) {8    $total→ 1 += $number1;9}
    All 4 passes — pass 1 is the card above
    pass$number$total
    110 1
    221 3
    333 6
    446 10
  3. print "limit=$limit ";

    11print "limit=$limit4\n";12print "total=$total10\n";
    outputlimit=4
    total=10
  1. $limit ← 2, $total ← 0

    4my $limit→ 2 = 2;5my $total→ 0 = 0;
  2. $total ← 1

    pass 1 of 2
    7for my $number1 (1..$limit2) {8    $total→ 1 += $number1;9}
  3. $total ← 3

    pass 2 of 2
    7for my $number2 (1..$limit2) {8    $total→ 3 += $number2;9}
  4. print "limit=$limit ";

    11print "limit=$limit2\n";12print "total=$total3\n";
    outputlimit=2
    total=3
  1. $limit ← 6, $total ← 0

    4my $limit→ 6 = 6;5my $total→ 0 = 0;
  2. $total ← 1

    pass 1 of 6
    7for my $number1 (1..$limit6) {8    $total→ 1 += $number1;9}
    All 6 passes — pass 1 is the card above
    pass$number$total
    110 1
    221 3
    333 6
    446 10
    5510 15
    6615 21
  3. print "limit=$limit ";

    11print "limit=$limit6\n";12print "total=$total21\n";
    outputlimit=6
    total=21

What Happens

  1. $limit starts at 4.
  2. $total starts at 0.
  3. The loop visits 1, 2, 3, and 4.
  4. Each number is added to $total.
  5. The program prints limit=4 and total=10.

Loop Picture

| limit | numbers added | total | | --- | --- | --- | | 2 | 1, 2 | 3 | | 4 | 1, 2, 3, 4 | 10 | | 6 | 1, 2, 3, 4, 5, 6 | 21 |

Try It

Exercise: loops.pl

Reproduce total=10 for limit 4, then use the pinned limits 2 and 6 to predict each total.