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

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


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)