1. Perl
  2. Syntax
  3. for statement

for statement - Loop syntax

for statement is the syntax for loop.

# for statement
for (InitializeCounterVariable; Condition; UpdateCounterVariable) {
  ...
}

The repetition using for statement is explained in detail below.

Other loop syntaxes

Other loop syntaxes are while statement and foreach statement. foreach statement is the merely alias for for statement.

Example

Examples of for statements.

Array

This is an example that outputs the elements of the array in order.

# Iterate array elements
my @nums = (3, 4, 5);
for (my $i = 0; $i < @nums; $i++) {
  print "$i:" . $nums[$i] . "\n";
}

Output:

0:3
1:4
2:5

Array reference

This is an example that outputs the elements of an array in order when the data structure is an array reference.

# Iterate array elements when the data structure is an array reference
my $nums = [3, 4, 5];
for (my $i = 0; $i < @$nums; $i++) {
  print "$i:". $nums->[$i] . "\n";
}

Output:

0:3
1:4
2:5

2D array

This is an example that outputs all the elements of a two-dimensional array in order. In Perl, 2D arrays is created by using reference.

# Output all elements of 2D array
my $data = [
  ['a', 1],
  ['b', 2]
];

for (my $i = 0; $i < @$data; $i++) {
  for (my $k = 0; $k <@{$data->[$i]}; $k ++) {
    print "($i, $k):". $data->[$i]->[$k] . "\n";
  }
}

Output:

(0, 0):a
(0, 1):1
(1, 0):b
(1, 1):2

Join with tab

This is an example that outputs the values contained in the two-dimensional array, separated by tabs for each line.

# Output 2D array line by row, separated by tabs
my $data = [
  ['a', 1],
  ['b', 2]
];;

for (my $i = 0; $i < @$data; $i++) {
  print join("\t", @{$data->[$i]}) . "\n";
}

Output:

a	1
b	2

Output strings

Here are some examples of for statement.

use strict;
use warnings;

print "[1]\n";
for (my $i = 0; $i < 5; $i++) {
  print "$i\n";
}
print "\n";

print "[2]\n";
my @chars = qw(a b c d e);
for (my $i = 0; $i < @chars; $i++) {
  print "$chars[$i]\n";
}
print "\n";

Output:

[1]
0
1
2
3
4

[2]
a
b
c
d
e

Related Informatrion