views:

190

answers:

3

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?

+8  A: 

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. :-)

cjm
+8  A: 

Must you use a for loop? Copy the original and 'consume' it with shift:

use strict;
use warnings;

my @original = 'a' .. 'z';    # Original
my @array = @original;        # Copy

while (my $token = shift @array) {

    shift @array if $token =~ /[nr]/; # consumes the next element
    print $token;
}

# prints 'abcdefghijklmnpqrtuvwxyz' ('s' and 'o' are missing)
Zaid
Nice. In my case, destroying original is not even a problem, so I can do without the copy.
Thilo
+4  A: 

Starting with Perl 5.12, each is now more flexible by also working on arrays:

use 5.012;
use warnings;

my @tokens = 'a' .. 'z';

while (my ($i, $val) = each @tokens) {
    if ($val =~ m/[aeiou]/) {
        ($i, $val) = each @tokens;   # get next token after a vowel
        print $val;
    }
}

# => bfjpv


One caveat with each, remember the iterator is global and is not reset if you break out of a loop.

For eg:

while (my ($i, $val) = each @tokens) {
    print $val;
    last if $i == 12;
}

# => abcdefghijklm

my ($i, $val) = each @tokens;
say "Now at => $val ($i)";         # Now at => n (13)

So use keys or values to manually reset the iterator:

keys @tokens;                      # resets iterator
($i, $val) = each @tokens;
say "Now at => $val ($i)";         # Now at => a (0)

/I3az/

draegtun