Home > Enterprise >  Perl: Go to further processing only if there are no elements to be processed by foreach loop of arra
Perl: Go to further processing only if there are no elements to be processed by foreach loop of arra

Time:07-01

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";
}

CodePudding user response:

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";
}

CodePudding user response:

Depending on how you want to handle empty arrays:

for my $i ( @array ) {
    print "I am inside array\n";
}

print "i did this because there is no elements afterwards in array\n";

or

for my $i ( @array ) {
    print "I am inside array\n";
}

if ( @array ) {
    print "i did this because there is no elements afterwards in array\n";
}

The last element is $array[-1], if you want it.

CodePudding user response:

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.

  • Related