bubble
bubble

Reputation: 3526

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

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?

Upvotes: 2

Views: 340

Answers (3)

Zaid
Zaid

Reputation: 37146

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];
    # ...
}

Upvotes: 6

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74222

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
}

Upvotes: 7

user507077
user507077

Reputation:

Two ideas:

First, if you always need a pair of consecutive rows then you could remember the previous row, e.g.

my $prev_row;
foreach my $row (@rows) {
  # Skip first row; we don't have a previous one yet
  if (!$prev_row) {
    $prev_row = $row;
    next;
  }

  # Do stuff with $prev_row and $row

  $prev_row = $row;
}

Second, use the normal C-style for loop. In that case you have indices and can actually access any required element all the time:

# don't iterate over the last line so not to access beyond the array
for (my $idx = 0; $idx < (scalar(@rows) - 1); $idx++) {
  my $row      = $rows[$idx];
  my $next_row = $rows[$idx + 1];
}

You cannot do it with a "simple" foreach just by using the current element only. It's not an interator, it's a reference to the current element from that list.

Upvotes: 5

Related Questions