Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pull the next element from within a Perl foreach loop?

Can I do something like the following in Perl?

foreach (@tokens) {
     if (/foo/){
       # simple case, I can act on the current token alone
       # do something
       next;
    }
    if (/bar/) {
       # now I need the next token, too
       # I want to read/consume it, advancing the iterator, so that
       # the next loop iteration will not also see it
       my $nextToken = .....
       # do something
       next;
    }

}

Update: I need this in Perl, but for curiosity's sake: Do other languages have a neat syntax for that?

like image 805
Thilo Avatar asked Jun 05 '10 08:06

Thilo


2 Answers

Not with a foreach loop. You can use a C-style for loop:

for (my $i = 0; $i <= $#tokens; ++$i) {
  local $_ = $tokens[$i];
  if (/foo/){
     next;
  }
  if (/bar/) {
    my $nextToken = $tokens[++$i];
    # do something
    next;
  }
}

You could also use something like Array::Iterator. I'll leave that version as an exercise for the reader. :-)

like image 127
cjm Avatar answered Sep 18 '22 04:09

cjm


    my $arr = [0..9];

    foreach ( 1 ..  scalar @{$arr} ) {

           my $curr = shift @{$arr};

           my $next = shift @{$arr};

           unshift @{$arr} , $next;

           print "CURRENT :: $curr :: NEXT :: $next \n";
    }
like image 45
plichev Avatar answered Sep 21 '22 04:09

plichev