Multiple ways iterate an array in Perl(Examples)
Perl arrays are a group of ordered values assigned to a variable. values are scalar types in Perl.
The array can be declared with the @
sign
@numbers = (11, 22, 33,44,55,66);
A single element can be read using an array variable with the dollar($) sign with an index.
print "$numbers[0]\n";
This tutorial explains multiple ways to iterate an array in Perl.
Iterate an array using for loop
- Array is declared and assigned with a list of numbers
- used
for
loop and do iteration, assign an iterated element to$item
- Print each element using the
print
statement
Here is an example
@numbers = (11, 22, 33,44,55,66);
for my $item (@numbers) {
print "$item\n";
}
Output:
11
22
33
44
55
66
Iterate an array with index and element using for loop
- Array is declared and assigned with the list of numbers
- used
for
loop, Loop values with starting index=0, followed by range operator(..
) and end index. The end index can be retrieved with$=
array variable. So, Generates sequential index numbers - Iterate with index variable
$i
- Print each element using the
print
statement, which contains syntax to retrieve an element using index$numbers[$i]
Here is a for loop with index and element example
@numbers = (11, 22, 33,44,55,66);
for my $i (0 .. $#numbers) {
print "$i - $numbers[$i]\n";
}
Output:
0 - 11
1 - 22
2 - 33
3 - 44
4 - 55
5 - 66
Loop an array using while and each loop
These examples are required when you need an index and element for looping an array in Perl. This works in Perl 5.12 version onwards.
- used
each
with array variable in thewhile
loop - Each iteration returns an object of
index
andelement
. - Print an index and element
Here is an example
@numbers = (11, 22, 33,44,55,66);
while (my ($index, $element) = each @numbers) {
print "$index - $element\n";
}
Loop elements in an array using a foreach loop
- Array is declared and assigned with a list of numbers
- used
foreach
loop and do iteration, assign an iterated element to$item
- Print each element using the
print
statement
Here is an example
@numbers = (11, 22, 33,44,55,66);
foreach my $item (@numbers) {
print "$item\n";
}
Output:
11
22
33
44
55
66
Conclusion
In terms of speed, foreach
iteration is faster compared with all other approaches.