Reputation: 359
How can I check if no elements exist further in the array to be processed by the foreach loop?
Example:
my @array = ("abc","def","ghi");
foreach my $i (@array) {
print "I am inside array\n";
#####'Now, I want it further to go if there are no elements after
#####(or it can be said if it is the last element of array. Otherwise, go to next iteration'
print "i did this because there is no elements afterwards in array\n";
}
I could think of ways to do this, but wondering if I can get it in a short way, either using a specific keyword or function. One way I thought:
my $index = 0;
while ($index < scalar @array) {
##Do my functionality here
}
if ($index == scalar @array) {
print "Proceed\n";
}
Upvotes: 1
Views: 92
Reputation: 66883
One way to detect when processing is at the last element
my @ary = qw(abc def ghi);
foreach my $i (0..$#ary) {
my $elem = $ary[$i];
# work with $elem ...
say "Last element, $elem" if $i == $#ary;
}
The syntax $#array-name
is for the index of the last element in the array.
Note also that each works on arrays, useful if there are uses of indices
while (my ($i, $elem) = each @ary) {
# ...
say "Last element, $elem" if $i == $#ary;
}
Then make sure to read docs to be aware of subtleties of each
.
Upvotes: 2
Reputation: 385647
Depending on how you want to handle empty arrays:
for my $ele ( @array ) {
say $ele;
}
say "Proceed";
or
for my $ele ( @array ) {
say $ele;
}
if ( @array ) {
say "Proceeding beyond $array[-1]";
}
Upvotes: 1
Reputation: 6798
There are multiple ways to achieve desired result, some based on usage of $index
of array, and other based on use $#array-1
which can be utilized to obtain the array slice, the last element of an array accessible with $array[-1]
.
use strict;
use warnings;
use feature 'say';
my @array = ("abc","def","ghi");
say "
Variation #1
-------------------";
my $index = 0;
for (@array) {
say $index < $#array
? "\$array[$index] = $array[$index]"
: "Last one: \$array[$index] = $array[$index]";
$index++;
}
say "
Variation #2
-------------------";
$index = 0;
for (@array) {
unless ( $index == $#array ) {
say "\$array[$index] = $_";
} else {
say "Last one: \$array[$index] = $_";
}
$index++;
}
say "
Variation #3
-------------------";
$index = 0;
for( 0..$#array-1 ) {
say "\$array[$index] = $_";
$index++;
}
say "Last one: \$array[$index] = $array[$index]";
say "
Variation #4
-------------------";
for( 0..$#array-1 ) {
say $array[$_];
}
say 'Last one: ' . $array[-1];
say "
Variation #5
-------------------";
my $e;
while( ($e,@array) = @array ) {
say @array ? "element: $e" : "Last element: $e";
}
Upvotes: 2