Search⌘ K
AI Features

Looping Directives: foreach, for

Learn how to use Perl's looping directives foreach and for to iterate over lists efficiently. Understand how the keyword and iterator variables work, including scope and lexical declaration, to write clear and maintainable Perl loops.

The looping directives

Perl provides several directives for looping and iteration.

The foreach and for directives

The foreach-style loop evaluates an expression that produces a list and executes a statement or block until it has exhausted that list:

Perl
foreach (1 .. 10) {
say "$_ * $_ = ", $_ * $_;
}

This example uses ...