Ad space (banner)
Lesson 5 / 20

Repeating (the for loop)

This lesson covers looping in Perl with a for statement.

Writing for (init; condition; update) { ... } repeats a block a fixed number of times, much as in C.

The sample code writes for (my $i = 1; $i <= 5; $i++) to print the numbers 1 through 5 in order.

A common early stumble is that the loop variable needs both my and $. The shape resembles other languages, but Perl's sigils still have to be there.

In professional work, for loops are used to process every element of an array, and the foreach form covered with arrays in the next lesson is just as common.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Perl directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)