1. Perl
  2. Syntax
  3. foreach statement

foreach - Processing of each element of the array

Use foreach statement to iterate the elements of the array.

foreach my $element (@array) {
  ...
}

In Perl, foreach is the alias for for statement, so you can use for instead of foreach.

for my $element (@array) {
  ...
}

The way to output the elements of a array is explained in detail on the following article.

Other loop syntaxes

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

Example

Examples of foreach statement.

Array

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

# Output array elements in order
my @nums = (3, 4, 5);
foreach my $num (@nums) {
  print "$num\n";
}

Output:

3
4
5

Array reference

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

# Output array elements in sequence (array reference)
my $nums = [3, 4, 5];
foreach my $num (@$nums) {
  print "$num\n";
}

Output:

3
4
5

2D array

This is an example that outputs the values contained in the two-dimensional array, separated by tabs for each line. join function is used to connect the strings contained in the array with tabs.

# Output the values contained in the 2D array in tabs for each line
my $data = [
  ['a', 1],
  ['b', 2]
];;

foreach my $record (@$data) {
  print join("\t", @$record) . "\n";
}

Output:

a	1
b	2

Join with tab

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

# Outputs the values contained in the hash array, tab-separated line by line
my $persons = [
  {name =>'Ken', age => 19},
  {name =>'Taro', age => 32}
];;

foreach my $person (@$persons) {
  my @record = ($person->{name}, $person->{age});
  print join("\t", @record) . "\n";
}

Output:

Ken	19
Taro	32

Output strings

Here are some examples of foreach.

use strict;
use warnings;

print "[1]\n";
my @persons = ('tom', 'taro', 'sinji');
foreach my $person (@persons) {
  print $person, "\n";
}
print "\n";

print "[2]\n";
my @numbers = (1, 2, 3);
foreach my $number (@numbers) {
  # Since what is passed to $number is an alias for the element, you can change the value of the array itself.
  $number = $number * 2;
}
print "\@numbers = (", join(',', @numbers), ")\n\n";

print "[3]\n";
foreach my $index(0 .. $# persons) {
  # When you want to use the index, pass the index without passing the element of the array itself.
  print "\$persons[$index] = $persons[$index]\n";
}

Output:

[1]
tom
taro
sinji

[2]
@numbers = (2,4,6)

[3]
$people[0] = tom
$persons[1] = taro
$persons[2] = sinji

Related Informatrion