1. Perl
  2. here

Iterative processing using for/while statement

Learn about Perl's iterative syntax. Learning the iterative syntax greatly expands the range of programs.

Basics of for statement

First, I will explain the iterative syntax for statement . Take a look at the following example first. This is a program that outputs a number from 0 to 9 on the screen.

for (my $i = 0; $i < 10; $i++) {
  print "$i\n";
}

The output result of this is as follows. The number from 0 to 9 is output.

0
1
2
3
Four
Five
6
7
8
9

Let's explain the syntax in order. for statement has the following syntax.

for (Initialization of loop variable; Condition to loop; Update of loop variable) {
  ...
}

1. Initialization of loop variable

The first part is the initialization of the loop variable. This part determines what value the loop variable starts with first. Think of a loop variable as a variable used within a loop.

Let's look at the first example again. Notice the part "my $i = 0".

for (my $i = 0; $i < 10; $i++) {
  print "$i\n";
}

In the initialization part of the loop variable, variable declarations can be made at the same time. We declare a variable called "$i" and initialize it with "0".

What if this part is "my $i = 5"?

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

Since "$i" is initialized with "5", the output result will be as follows.

Five
6
7
8
9

2. Looping conditions

Now let's look at the conditions for looping.

for (Initialization of loop variable; Condition to loop; Update of loop variable) {
  ...
}

for statement repeatedly executes the block while the looping condition is met. Looking at the first example, the condition is that "$i" is less than "10".

for (my $i = 0; $i < 10; $i++) {
  print "$i\n";
}

So the block will be executed while "$i" is less than "10".

What if this part is "$i < 7"?

for (my $i = 0; $i < 7; $i++) {...}

The output result is as follows. Since "$i" loops while it is less than "7", you can see that it is output up to "6".

0
1
2
3
Four
Five
6

3. Update loop variable

Finally, I will explain the update part of the loop variable.

for (Initialization of loop variable; Condition to loop; Update of loop variable) {
  ...
}

In the loop variable update part, you can change the value of the loop variable before executing the next block.

for (my $i = 0; $i < 10; $i++) {
  print "$i\n";
}

In the first example, it is written as "$i++". This is called increment and you can increment the value of $i by 1.

The value of "$i" is incremented by 1 before proceeding to the next loop. In other words, each time you go through the loop, it will increase to "1", "2", "3".

What if this part is "$i += 2"? This is special assignment operator that allows you to increment the value of "$i" by "2".

for (my $i = 0; $i < 10; $i += 2) {
  print "$i\n";
}

The output will be as follows, as it will increase by two.

0
2
Four
6
8

Make sure you are looping from "0" to "2" and less than "10".

For statement example program

I think that the iterative syntax will be easier to understand if you actually run some examples.

Output from "9" to "0" for the first time

Next, let's look at a program that outputs from "9" to "0" for the first time.

for (my $i = 9; $i >= 0; $i- ) {
  print "$i\n";
}

Since it is initialized as "my $i = 9", "$i" starts with "9". Since the condition is "$i >= 0", it is repeated when "$i" is "0 or more". The final "$i- " decrements the value of "$i" by one before moving on to the next loop. "-" Is decrement operator that decrements the value of a variable by "1".

The output result is as follows.

9
8
7
6
Five
Four
3
2
1
0

Output from "9" to "1" for the first time by skipping two

Next, I will skip two and output from "9" to "1".

for (my $i = 9; $i >= 0; $i-= 2) {
  print "$i\n";
}

Since the update part of the loop variable is "$i-= 2", the value of "$i" is reduced by "2" before entering the next loop.

The output result is as follows.

9
7
Five
3
1

Combining for and if statement

Let's combine for statement and if statement. Programming will improve when you can combine for and if statement.

I will write an example program that loops from "0" to "10", but outputs only when the loop variable is a multiple of 3.

for (my $i = 0; $i < 10; $i++) {
  if ($i % 3 == 0) {
    print "$i\n";
  }
}

Please pay attention to the conditional branch part using if statement. You can confirm that "$i" is a multiple of "3" by writing "$i % 3 == 0". This is because if the remainder after dividing by "3" is "0", that number is a multiple of 3.

Please refer to the following articles for the modulo operator.

Since if statement block is executed only when it is a multiple of 3, the output result is as follows.

0
3
6
9

Combining if and for statement gives you better control over your program. Please refer to the following article for a detailed explanation of if statement.

while statement

Next, let's learn about while statement. while statement is a syntax for looping like for statement.

The difference from for statement is that while statement has only the "looping condition" part. Take a look at the following example.

my $i = 0;

while ($i < 10) {
  
  print "$i\n";
  
  $i++;
}

When this is executed, the number from "0" to "9" will be output to the screen.

0
1
2
3
Four
Five
6
7
8
9

The part "$i < 10" is the part of the condition that loops in while statement. Unlike for statement, while statement does not have an initialization part or a loop variable update part.

while (condition to loop) {...}

The "Initialize loop variable" and "Update loop variable" parts must be written as Perl statement.

# Initialization of loop variable
my $i = 0;

while ($i < 10) {
  
  print "$i\n";
  
  # Update loop variable
  $i++;
}

The above while statement example corresponds to the following for statement.

for (my $i = 0; $i < 10; $i++) {
  print "$i\n";
}

for statement is simpler to write. If you need a loop variable, for statement is easier to write.

foreach statement

The foreach statement can be used to process the elements of array in sequence. Take a look at the following example program.

my @animals = ('Cat', 'Dog', 'Mouse');

foreach my $animal (@animals) {
  print "$animal\n";
}

This is a program that outputs the elements of the array ('Cat', 'Dog', 'Mouse') in order. The output result is as follows.

Cat
Dog
Mouse

Same as for statement and foreach statement

In Perl, foreach statement is an alias for for statement, and you can also write for where you should write foreach.

my @animals = ('Cat', 'Dog', 'Mouse');

for my $animal (@animals) {
  print "$animal\n";
}

Looking at how to write Perl these days, I think I tend to always use for rather than foreach. I think it feels like it settles down on the shorter side.

Use with range operator

It can also be used with range operator.
for my $num (3 .. 6) {
  print "$num\n";
}

next statement

You can use next statement to jump to the beginning of the next iteration. Take a look at the following example program.

my @nums = (3, 5, 6, 7);
for my $num (@nums) {
  if ($num == 5) {
    next;
  }
  print "$num\n";
}

The elements of the array (3, 5, 6, 7) are output, but only when "$num" is "5", it jumps to the beginning of the next iteration. The output result is as follows.

3
6
7

Only when it is "5", the "print function" is not executed because it jumps to the beginning of the loop.

last statement

You can use last statement to end the iteration and escape for statement. Take a look at the following example program.

my @nums = (3, 5, 6, 7);
for my $num (@nums) {
  if ($num == 6) {
    last;
  }
  print "$num\n";
}

It outputs the elements of the array (3, 5, 6, 7), but exits the loop when "$num" is "6". Therefore, the output result is as follows.

3
Five

I introduced an example of combining with for here, but next and for can also be used in while statement.

Use for, while, and foreach properly

I explained the syntax of the three iterations, but you may feel that "how do you actually use them properly?" Therefore, I will write a guideline for proper use.

First, think about whether you can write with foreach

First of all, think about whether you can write using foreach. Foreach is the easiest way to write a loop, so if foreach is enough, use foreach. It's common to process the elements of an array in sequence, but you can write this in foreach.

my @animals = ('Cat', 'Dog', 'Mouse');

foreach my $animal (@animals) {
  print "$animal\n";
}

Or write as follows using the alias for.

my @animals = ('Cat', 'Dog', 'Mouse');

for my $animal (@animals) {
  print "$animal\n";
}

First, consider whether you can write this way.

When an index is required, a normal for statement

Next, suppose you may need the index. In that case, use the normal for statement. The following example program outputs the indexes and array elements. Note that you can get the length of the array by evaluating "@animals" in a scalar context.

my @animals = ('Cat', 'Dog', 'Mouse');

for (my $i = 0; $i < @animals; $i++) {
  my $animal = $animals[$i];
  print "$i: $animal\n";
}

The output result is as follows.

0: Cat
1: Dog
2: Mouse

While statement for repetition that does not increase the index

Finally, use while statement if the repetition does not increase the index. Here are some common examples.

1. Read a line from a file

Use while statement to read a line from a file.

while (my $line = <>) {
  print $line;
}

File I/O is explained in detail below.

2. Pop an array

Use while statement to write the process such as ending when the array is extracted using the pop function and disappears.

my @animals = ('Cat', 'Dog', 'Mouse');

while (my $animal = pop @animals) {
  print "$animal\n";
}

The output result is as follows.

Mouse
Dog
Cat

When popped and emptied, the loop ends.

3. I want to write an infinite loop

If you want to write an infinite loop, use while statement. If the condition is set to 1, while statement will continue to be executed.

while (1) {
  # process
}

Use last if you want to get out of an infinite loop when some condition is met.

while (1) {
  # process
  
  if ($flag) {
    last;
  }
}

Multidimensional data structures and iterations

Finally, I will write a multidimensional data structure and a repetitive example program. In Perl, we often use a data structure called an array of hashes, so I'll write an example of it.

# Hash array example program
my $students = [
  {name =>'kimoto', age => 36},
  {name =>'kana', age => 21},
  {name =>'jiro', age => 56}
];;

for my $student (@$students) {
  my $name = $student->{name};
  my $age = $student->{age};
  
  print "Name: $name, Age: $age\n";
}

The output result is as follows.

Name: kimoto, Age: 36
Name: kana, Age: 21
Name: jiro, Age: 56

Here, "[]", "{}", "@$students", and "$student->{name}" that have never been explained have appeared. This is a Perl syntax called a reference. The processing of multidimensional data structures is explained in detail below, so please refer to it.

Functions for writing loops easily

grep function

Perl has grep function that allows you to retrieve only matching elements of an array.

my @matches = grep {$_ > 5} @values;

This is the same as writing the following in for statement, but more concisely.

my @matches;
for my $value (@$values) {
  if ($value > 5) {
    push @matches, $value;
  }
}

map function

Perl has map function that makes it easy to write transformations of all array elements.

my @values2 = map {"$_. Txt"} @values1;

This is the same as writing the following in for statement, but more concisely.

my @values2;
for my $value1 (@values1) {
  my $value2 = "$value1.txt";
  push @values2, $value2;
}

Postfix for - for modifier

A special for syntax is the for modifier, which allows you to put a for after a statement. If you can write for statement in one line, this writing method is also simple.

Below is an example that outputs all the elements of the array. The elements of the array are sequentially assigned to the default argument "$_".

my @values = (3, 4, 5);
print "$_\n" for @values;

For readability, it's a good idea to always use a regular for statement.

But in fact, the postfix for has a clear advantage. That is, the postfix for does not create a scope, so it performs better than a normal for .

Performance shouldn't be an issue for most programs you write in your day-to-day business. However, if you can execute it in one line and you really want to gain speed, you should use the postfix for.

Related Informatrion