我可以在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;
}
}
更新:我需要在Perl中使用它,但出于好奇心的缘故:其他语言是否有一个简洁的语法?
答案 0 :(得分:19)
您必须使用for
循环吗?复制原始文件并使用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)
答案 1 :(得分:9)
从Perl 5.12开始,each is now more flexible还要处理数组:
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
对each
的一个警告,记住迭代器是全局的,如果你突破循环就不会重置。
例如:
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)
keys @tokens; # resets iterator
($i, $val) = each @tokens;
say "Now at => $val ($i)"; # Now at => a (0)
答案 2 :(得分:8)
没有foreach
循环。您可以使用C风格的for
循环:
for (my $i = 0; $i <= $#tokens; ++$i) {
local $_ = $tokens[$i];
if (/foo/){
next;
}
if (/bar/) {
my $nextToken = $tokens[++$i];
# do something
next;
}
}
您还可以使用Array::Iterator之类的内容。我将把这个版本留给读者练习。 : - )
答案 3 :(得分:0)
我喜欢Zaids的答案,但是如果遇到数组中的null元素则会失败 所以...
while (@array) {
my $token = shift @array;
shift @array if $token =~ /[nr]/; # consumes the next element
print $token;
}
在@array
为空之前不会停止。
答案 4 :(得分:0)
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";
}