THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.
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.
for
loop and do iteration, assign an iterated element to $item
print
statementHere is an example
@numbers = (11, 22, 33,44,55,66);
for my $item (@numbers) {
print "$item\n";
}
Output:
11
22
33
44
55
66
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$i
print
statement, which contains syntax to retrieve an element using index $numbers[$i]
Here is an 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
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.
each
with array variable in the while
loopindex
and element
Here is an example
@numbers = (11, 22, 33,44,55,66);
while (my ($index, $element) = each @numbers) {
print "$index - $element\n";
}
foreach
loop and do iteration, assign iterated element to $item
print
statementHere is an example
@numbers = (11, 22, 33,44,55,66);
foreach my $item (@numbers) {
print "$item\n";
}
Output:
11
22
33
44
55
66
In terms of speed, foreach
iteration is faster compared with all other approaches.
🧮 Tags
Recent posts
Julia examples - Variable Type Nim example - Convert String to/from the Int How to get length of an array and sequence in Nim? Nim environment variables - read, set, delete, exists, and iterate examples? How to convert from single character to/from string in Nim?Related posts