繁体   English   中英

如何使用值数组来限制perl中的for循环?

[英]How do I use an array of values to limit a for loop in perl?

我知道这个问题相当含糊,但我希望解释的空间可以帮助解决问题,这是我整天都在捣乱我的大脑,并且通过搜索找不到任何建议。

基本上我有一个数组@cluster,我试图使用迭代器$ x跳过位于该数组中的值。 这个数组的大小会有所不同,所以我不能只是(相当恶劣地)使if语句不幸地适合所有情况。

通常,当我需要使用标量值执行此操作时,我只需执行以下操作:

for my $x (0 .. $numLines){
    if($x != $value){
        ...
    }
}

有什么建议?

你可以做:

my @cluster = (1,3,4,7);
outer: for my $x (0 .. 10){
    $x eq $_ and next outer for @cluster;
    print $x, "\n";
}

使用Perl 5.10,您还可以:

for my $x (0 .. 10){
    next if $x ~~ @cluster;
    print $x, "\n";
}

或者更好地使用哈希:

my @cluster = (1,3,4,7);
my %cluster = map {$_, 1} @cluster;
for my $x (0 .. 10){
    next if $cluster{$x};
    print $x, "\n";
}

嗯......如果您要跳过线路,为什么不直接使用该标准而不是记住需要过滤的线路?

grep函数是一个用于过滤列表的强大构造:

my @array = 1 .. 10;

print "$_\n" for grep { not /^[1347]$/ } @array;  # 2,5,6,8,9,10
print "$_\n" for grep {     $_ % 2     } @array;  # 1,3,5,7,9

my @text = qw( the cat sat on the mat );

print "$_\n" for grep { ! /at/ } @text;           # the, on, the

更不用杂乱了,还有更多的DWIM!

窦你的意思是这样的:

for my $x (0 .. $numLines){
    my $is_not_in_claster = 1;
    for( @claster ){
         if( $x == $_ ){
             $is_not_in_claster = 0;
             last;
         }
    }
    if( $is_not_in_claster ){
        ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM