Last Updated:

Loop operators | Perl

It is known that for the implementation of any algorithm, three control structures are enough: sequential execution, condition branching and a loop with a precondition. Any programming language provides the programmer with a set of all three control constructs, supplementing them for ease of programming with other constructions: branch chains and various forms of the loop with a precondition, as well as loops with a postcondition.

We've already seen the Perl branching operators, and now it's time to learn which loop constructs can be used in Perl. There are only three of them: whilefor and foreach. All of them belong to the class of composite operators and, of course, are defined in terms of block blocks.

while and until loops

The while loop is designed to recalculate a block of statements as long as the condition expression specified in it remains true. Its general syntax takes two forms:

LABEL while (EXPRESSION) BLOCK
LABEL while (EXPRESSION) BLOCK continue BLOCK1

All loop statements may not be labeled. In Perl, the label represents the correct identifier, ending with a colon ":". It's important for the next navigation command, which we'll talk about in the next section.

The while statement follows the following pattern. Expression-condition expressions are evaluated. If it is true, then block operators are executed. Otherwise, the loop statement terminates and passes control to the next program operator (loop 1 of Example 5.5). Thus, the while loop operator is a loop control construct with a precondition: first, the condition for the completion of the loop is checked, and then only the body of the loop determined by the BLOCK operators. Therefore, it may turn out that the body of the cycle will not be fulfilled even once if the condition turns out to be false when it enters the loop for the first time (cycle 3 of Example 5.5).

Instead of the while keyword, you can use the until keyword. In this case, the control construct is called a until loop, which differs from a parsed while loop in that its body is executed only if the expression of the condition is false (loop 2 of Example 5.5).

#perl-w
# loop 1
$i = 1;
while <$i<= 3) {
$a[$i] = l/$i; # Assign a value to an array element
++$i; >
print "Loop variable \$i = $i\n";
# $i = 4 print "Array \@a: @a\n"; # @a = <strong>(I</strong>, 0.5. 0.333333333333333)
# loop 2, equivalent to the previous one
$i = 1;
until ($i > 3) {
$a[$i] = l/$i; # Assign a value to an array element
++$i; }
print "Loop variable \$i = $i\n";
# $i = 4 print "Array \@a: @a\n"; # @a = (1, 0.5. 0.333333333333333)
# loop 3, the body of the loop is not executed even once
$i = 5;
while ($i-<= 3) {
$a[$i] = l/$i;
++$i; } print "Loop variable \$i = $i\n"; # $i = 5
# loop 4, infinite loop (does not change condition expression)
$i = 1;
while ($i <= 3) {
$a[$i] = l/$i; }.

Note that in the body of the loop there must be operators, the calculation of which leads to a change in the expression of the condition. Typically, these are operators that change the values of variables used in a condition expression. If this does not happen, the while or until loop will run indefinitely (loop 4 of example 5.5).

The postcondition
loop is implemented by applying the while modifier to the do() construct, and was discussed in section 5.2.2" While and until modifiers
.

The BLOCK! statement block specified after the continue keyword is executed whenever a new iteration is performed. This occurs after the last statement of the loop body is executed or when the next command explicitly switches to the next iteration of the loop. The continue block is rarely used in practice, but you can use it to strictly define a for loop through the while loop statement.

Example 5.6 demonstrates how to use a while loop to calculate degrees of two no higher than sixteenth. In this example, the while loop operator is functionally equivalent to a for loop. The continue block is executed each time the next iteration of the loop is completed, increasing the variable $i by one. It is equivalent to the expression of increasing/decreasing the for operator.

#perl-w
# Calculate powers of 2 $1 = <strong>I;</strong>
while ($i <= 16) {
print "2 to the power of $i: ", 2**$i, "\n"; } continue {
++$i; f Increment $i before next iteration }

Cycle for

When you execute while and until loops, you don't know in advance how many iterations you need to perform. Their number depends on many factors: the values of variables in the expression of the condition before the start of the cycle execution, their change in the body of the loop, the form of the condition expression itself, etc. But sometimes in the program it is necessary to perform a predetermined number of repetitions of a certain group of operators. For example, read 5 lines from the file and modify them according to certain rules. Of course, you can program such a task with the statements of the while and until loop, but it may not look quite expressive. In the sense that when reading the program, you will have to "move" your brains a little before you understand the meaning of the loop operator. To solve such problems with a predetermined number of repetitions, the Perl language offers a special cycle construct – the for cycle:

LABEL for (EXPRESSION1; EXPRESSION2; EXPRESSION3) BLOCK 

EXPRESSION1 is used to set the initial values of the variables that control the loop, which is why it is called an initializing expression. Typically, these are one or more assignment operations separated by commas.

EXPRESSION2 defines the condition under which loop iterations will be repeated. It, like the condition expression of the while loop, must be true for the next iteration to begin. As soon as this expression becomes false, the for loop stops executing and passes control to the statement that follows it in the program.

EXPRESSION3 is responsible for increasing/decreasing the values of loop variables after the completion of the next iteration. Typically, it is a list of expressions with a side effect or a list of operations to assign new values to the variables of the loop. It is sometimes called a changing expression.

The algorithm for executing a loop for is as follows:

  1. An initializing expression (EXPRESSION!) is evaluated.
  2. The condition expression (vyrAGESHE2) is evaluated. If it is true, then the operators of the BLOCK block are executed, otherwise the loop completes its execution.
  3. After the next iteration is performed, the increase/decrease expression (EXPRESSION3) is evaluated and step 2 is repeated.

As noted in the previous section, the for loop is equivalent to a while loop with an continue block. For example, the following loop:

for ($i = 1; $i.<= 10; $i++) { }

... is equivalent to a while loop:

$i =1;
while ($i <= 10) {
} continue {
$i++; }

There is only one difference between these two cycles. A for loop defines the lexical scope for a loop variable. This allows you to use local variables declared with the mu function as loop variables:

$i = "global";
for (my $i = 1; $i <= 3; $i++) {
print "Inside the loop \$i: $i\n"; }
print "Outside loop \$i: $i\n ";

When you run this snippet of the program, the print operator will sequentially display values 1, 2, and 3 of the $1 local loop variable. When the loop exits, the local variable $i will be destroyed and the out-of-loop print statement will print the string global, the value of the $1 global variable defined outside the for loop.

All three statements in the for loop are optional and can be omitted, but the corresponding ",-" delimiters must be retained. If a condition expression is omitted, it is set to True by default. This allows you to organize an infinite loop:

for (;;) {
}

The exit from such a cycle is carried out by the management commands, which will be discussed in the next paragraph.

You can initialize a loop variable outside the loop, and you can change the value of a loop variable inside the loop body. In this case, initializing and modifying expressions are optional:

$i = 1;
for (; $i <= 3;) {
$i++; }

Tip
Although it is possible to change the loop variable in the body of the loop, it is not recommended to use it. The for loop was introduced into the language precisely in order to collect in one place all the operators controlling the work of the loop, which allows you to quickly change its behavior
.

for loop allows you to use multiple variables to control how the loop works. In this case, the initializing and modifying expressions use a comma operation. For example, if we want to create a hash in which the keys representing the digits from 1 to 9 correspond to the values of the same digits in reverse order from 9 to 1, then this problem can be solved by using a for loop with two loop variables:

for ($j = 1, $k = 9; $k >0; $j++, $k– ) {
$hash{$j} = $k; }

The same example shows that in a for loop, a loop variable can both increase and decrease. The main thing is that the condition expression correctly tracks the conditions for continuing iterations of the loop.

The for loop is a flexible enough construct that can be used for more than just implementing a loop with a predefined number of iterations. It allows you to use calls to built-in and user-defined functions in initializing and modifying expressions, rather than just defining and modifying loop variables. The main thing is to change the expression of the loop completion condition. Example 5.7 demonstrates just such a use of the for loop.

#perl-w
for (print "Enter data, press <strong>Enter</strong>\n" to complete input; <STDIN>;
print "Enter data, press <strong>Enter</strong>\n" to finish entering) {
last if $_eq "\n"; print "Entered string: $_"; }

In this example, the user enters rows of data in a loop. Before entering a new line, a tooltip is displayed using the print() function, which is defined in the modifying expression of the loop. The condition expression represents an input operation from a standard input file <STDIN>. Because this expression is evaluated whenever the loop moves to another iteration, the program will wait for keyboard input at each step of the loop. Exit the loop with the last command, which is invoked when the user enters an empty string. The entered data is stored in the built-in variable $_, and it also stores the character of transition to a new line, which is a sign of the completion of the data entry operation. Therefore, when you enter an empty string, the $_ variable actually stores the control sequence "\ n", with which the comparison is made to implement the exit from the loop.

Example 5.8 demonstrates a program that reads 3 lines of an egg.egg file. The read operation from the file is specified in the initializing and modifying expression, along with the definition and modification of the $1 loop variable.

#perl-w
open(FF, "err.err") or die "Error opening file";
for ($line=<FF>, $count = 1; $count <=3; $line=<FF>, $count++)
{
print "Line $count:\n $line\n";
t'}
close(FILE);

Foreach Loop

One of the most frequent uses of loops in programming languages is the organization of calculations with array elements: find the maximum element, print the elements of the array, find out whether there is an array element equal to a given value, etc. Such tasks are easily solved using while and for loops. Example 5.9 defines the maximum element of an array (assuming it contains numeric data).

#! peri – w
@array = (1,-6.9.18.0,-10);
$max = $array[0];,
for ($i = 1; $i <= $farray; $i++) {
$max = $array[$i] if $array[$i] > $max; }

After running Example 5.9, the $max variable will have a value of 18 equal to the maximum element of the $aggau array. Note that in the for loop (as in the while loop), access to the elements of the array is organized using an index.

In Perl, lists and arrays, which are essentially also lists, are such useful and frequently used constructs that a special foreach operator is provided in the language to loop through their elements, which has the following syntax:

LABEL foreach VARIABLE (LIST) BLOCK
LABEL foreach VARIABLE (LIST) BLOCK continue BLOCK

It loops through list items in the list by assigning the variable variable value to the selected list item at each step of the loop. The continue statement block is executed whenever the next iteration begins, except in the first iteration, when the variable $temp is equal to the first list item. A list can be specified either by a comma-separated sequence of values, by an array of scalars, or by a function whose return value is a list. The definition of the maximum element of an array can be overwritten with a foreach loop (Example 5.10).

#! peri, – w
Sarray = (1,-6.9.18.0,-10); $max = $array[0]; foreach $temp (Sarray) (
$max = $temp if $temp > $max; } print "$max";

At each step of the loop, the variable $temp sequentially takes the values of the elements of the $aggau array. Pay attention to the appearance of the program - in the absence of array indexes, it has become better readable.

Note a few features of the foreach cycle. First of all, it should be said that the foreach keyword is synonymous with the for keyword. The loop in Example 5.10 could also be written like this:

for $temp (@array) { # The foreach keyword is a synonym for for.
$max = $temp if $temp > $max; }

However, it seems to us that the use of foreach better reflects the semantics of this loop operator, since the keyword itself already reflects its essence (for each ).

The next feature of the foreach statement is related to the loop variable. By default, this variable is a local variable whose scope is limited by the body of the loop. It is created only for the duration of the foreach statement, is available inside the loop body, and is destroyed when the loop exits.

Typically, Perl programmers do not use a loop variable at all in foreach loops. This is because in the absence of an explicitly defined loop variable, Perl uses the special variable $_ by default. At each step of the loop, it will contain the value of a list item or array. With this fact in mind, the foreach loop of Example 5.10 can be rewritten as follows:

foreach (@array) { # Use $_ as loop variable.
$goax = $_ if $_ > $max;
} .l

A final feature of the foreach statement, which is also associated with a loop variable, is that at virtually every step of the loop execution, the variable is synonymous with the list item whose value it contains. This means that changing it in a loop changes the value of the corresponding list item. This property of the foreach loop is useful for changing the values of list items. Note that it can be applied to lists stored in arrays. For example, you can square each list item with the following foreach operator:

foreach $temp (@array) {
$temp **= 2; }

A list whose elements are looped can be specified not only explicitly by a constructor or array variable, but also by a function whose return value is a list. The canonical method of printing a hash array in an ordered order is shown in Example 5.11.

# peri – w %array = {
blue › 1,
red › 2,
green › 3,
yellow › 3); foreach (sort keys %array) {
print "$_\t › $array{$_}\n"; } '

This program will print the key/value pairs of the %aggau hash array according to the alphabetical order of its keys:

blue › 1
green › 3
red › 2
yellow › 3

The Remark
foreach loop is faster than the same for loop because it does not require the additional cost of calculating the index of the list item
.