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?
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. :-)
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";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With