Learn/Perl/5. Loops
Lesson 5 of 8
Sign in

Perl, lesson 5

Loops

Computers are good at doing the same thing many times. Perl has several loops; you will use foreach and while most of the time.

foreach over a range

The range operator .. builds a list of whole numbers, both ends included. foreach (or its shorter spelling for; they are the same keyword) takes each item in turn:

my $i makes a fresh variable that exists only inside the loop. A range only counts upward: 3 .. 1 is empty. To count down, reverse the list:

C-style for

When you need a custom step, Perl also has the three-part loop from C: a start, a condition checked before every pass, and an update after every pass:

while and until

while repeats as long as its condition is true. repeats as long as it is false.

2 exercises to try what you just read.

Exercise 1

Countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

until

Reading input line by line

This is one of the most common lines of Perl you'll ever write:

Each pass reads the next line. When the input runs out, <STDIN> returns undef and the loop ends. Perl quietly checks whether the line is defined rather than true, so a line containing just 0 doesn't stop the loop by accident.

last and next

  • last leaves the loop immediately (like break in other languages).
  • next skips the rest of this pass and starts the next one (like continue).

They pair nicely with postfix conditions:

When loops are nested, last and next affect the innermost one. You can give an outer loop a label (like ROW:) and write last ROW to leave it instead.

Further reading

  • perlsyn: Foreach loops
  • perlsyn: For loops
  • perlsyn: Loop control
  • perlop: Range operators

Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, and then Liftoff!.

Sample input:

Sample output:

Your fitness tracker sends one whole number per line: the steps walked each day. A line containing 0 marks the end of the data, and anything after it must be ignored. Print how many days came before the 0, and their total:

Sample input:

Sample output:

for my $i (1 .. 3) {
    print "Lap $i\n";
}
# Lap 1
# Lap 2
# Lap 3
for my $i (reverse 1 .. 3) {
    print "$i ";          # 3 2 1
}
print "\n";
for (my $i = 0; $i <= 10; $i += 5) {
    print "$i ";          # 0 5 10
}
print "\n";
my $fuel = 10;
while ($fuel > 0) {
    print "Fuel: $fuel\n";
    $fuel -= 4;
}
while (my $line = <STDIN>) {
    chomp $line;
    print "Got: $line\n";
}
for my $n (1 .. 100) {
    next if $n % 2;        # skip odd numbers
    last if $n > 10;       # stop after 10
    print "$n ";           # 2 4 6 8 10
}
print "\n";
3
3
2
1
Liftoff!
Days: <count>
Total: <sum>
4000
6500
3000
0
Days: 3
Total: 13500