2

我是 perl 的新手,并且在不重复循环的情况下跳到 foreach 循环内的数组的下一个元素时遇到了一些问题。假设我有以下情况,我正在使用 foreach 循环遍历数组。

 foreach (@lines){  
     ...  
     print "$_";     #print current line  
     if (cond){      #this condition is met by one "line" in @lines  
        #goto next line;  
        $_=~s/expr/substitute_expr/g;     #substitute in the next line  
      }  
     ...
 }

是否可以在 perl 中执行此操作。使用文件处理程序,可以使用 <> 运算符,如下所示

foreach $line (<FILE>){  
    print "$line\n";        #print this line  
    $line = <FILE>;  
    print "$line";        #print next line  
} 

有什么办法可以用数组复制它。
有没有办法在 使用 下一个 重复数组的情况下做到这一点

4

3 回答 3

3

您可以使用数组索引:

for my $i (0 .. $#lines) {
    # ...
    print $lines[$i];
    if (cond()) {
        $lines[ $i + 1 ] =~ s/pattern/replace/g;
    }
}

但是,这将在循环的下一次迭代中再次处理“下一个”行。如果你不想这样,你可以使用 C 风格:

for (my $i = 0; $i < $#list ; $i++) {
    # ...
}

更高级的技术是定义一个迭代器:

#!/usr/bin/perl
use warnings;
use strict;


sub iterator {
    my $list = shift;
    my $i = 0;
    return sub {
        return if $i > $#$list;
        return $list->[$i++];
    }
}


my @list = qw/a b c d e f g h/;
my $get_next = iterator(\@list);

while (my $member = $get_next->()) {
    print "$member\n";
    if ('d' eq $member) {
        my $next = $get_next->();
        print uc $next, "\n";
    }
}
于 2013-05-22T12:06:17.757 回答
0

这是对 choroba 的闭包答案的修改,它适用于所有数组(即包含 、 和 等值的数组0""undef因此执行起来更像典型的 foreach 循环。

#!/usr/bin/perl
use warnings;
use strict;

#!/usr/bin/perl
use warnings;
use strict;

sub iterator {
    my $list = shift;
    my $i = 0;
    return sub {
       if (defined $_[0] and $i > $#$list){
           return 0;
       }
       elsif (defined $_[0]){
           return 1;
       }
       else{
           return $list->[$i++];
       }
    }
}

my @list = qw/a b c d e f g h 0 1 2 3/;
my $get_next = iterator(\@list);

while ($get_next->("cycle through all array elements")) {
    my $member = $get_next->();
    print "$member\n";
    if ('d' eq $member) {
        my $next = $get_next->();
        print uc $next, "\n";
    }
}
于 2016-01-06T01:15:07.907 回答
-2

使用计数循环,如下所示:

use strict;
use warnings;

my @list = (1, 2, 3);
# as the item after the last can't be changed,
# the loop stops before the end
for (my $i = 0; $i < (scalar @list - 1); ++$i) {
    if (2 == $list[$i]) {
        $list[$i + 1] = 4;
    }
}

print join ',', @list;

输出:

perl countloop.pl
1,2,4
于 2013-05-22T12:04:55.487 回答