如何使用数组值来限制perl中的for循环?
这个问题我知道的很模糊,但我希望能够解释的空间可以帮助解决问题,这是我整天围绕我的大脑,并且无法通过搜索找到任何建议。如何使用数组值来限制perl中的for循环?
基本上我有一个数组@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";
}
豆你的意思是这样的:
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){
...
}
}
?
是的,这是做的工作,我希望perl有更优雅的东西,但这是一个相当复杂的逻辑陈述,谢谢! – Jash 2013-04-24 03:46:27
请注意,此解决方案必须在每个'$ x'的'@ claster'上循环,这会使'$ numLines'和'@ claster'的增长速度呈指数级下降。 – 2013-04-24 09:31:58
嗯......如果你正在跳过线条,为什么不直接使用该条件而不是记住需要过滤的行?
的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!
嗯,我没有真正实现任何使用Perl的grep函数的东西,它全部都是我在bash中的学习,但是在这里我从来没有想过。我会考虑将来的尝试,谢谢! – Jash 2013-04-25 14:58:04
你的意思是说'为我的$ x(@cluster)'? – perreal 2013-04-24 03:36:08
恰恰相反。我希望@cluster中的任何值不被使用。 我想我可以在我当前的$ x循环中使用另一个for循环,例如'for $ y(@cluster)'。 – Jash 2013-04-24 03:41:03
你如何知道你想跳过的值?它是等于一个特定的值还是处理了n值? – Glenn 2013-04-24 03:42:57