Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to jump iterator to point any other element of a list in foreach loop?

Tags:

perl

I have a foreach loop something like

foreach my $ref_array (@$array1)

where $array is the result of reading an entire Excel sheet.

Inside my loop $ref_array gets the value of each row in the sheet. Now I want to advance $ref_array such that it gets the value of next row of the spreadsheet. How shall I do it in the middle of the loop?

like image 977
bubble Avatar asked Jan 31 '26 08:01

bubble


2 Answers

Looping from 0 to the last array index $#$array1 would allow you to access the next row/element easily:

for my $index ( 0 .. $#$array1 ) {
    my ( $current, $next ) = @$array1[ $index, $index + 1 ];
    # Process the rows
}
like image 194
Alan Haggai Alavi Avatar answered Feb 01 '26 22:02

Alan Haggai Alavi


A Perl 5.12.0+ alternative:

for ( my ( $idx, $row ) = each @$array1 ) {

    last if $idx == $#array1;         # Skip last iteration

    my $next_row = $array1->[$idx+1];
    # ...
}
like image 44
Zaid Avatar answered Feb 01 '26 22:02

Zaid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!