问题描述
我刚刚遇到了一些我真的无法解释的非常奇怪的行为:
I've just encountered some very weird behavior that I really can't explain:
do {
my $qry = $self->getHTMLQuery(undef, $mech->content());
next if (!defined($qry));
push(
@prods,
map { 'http://www.XXXXYYYX.com'.$_->attr('href') }
$qry->query('div.prodInfo div.prodInfoBox a.prodLink.GridItemLink')
);
$qry->delete();
$TEST++;
last if ($TEST >= 10);
} while(eval { $mech->follow_link(class => 'jump next') });
print "WHILE ENDED\n";
上面的代码从不打印WHILE ENDED",即使当 $TEST
>= 10 时它似乎确实退出了 while 循环.
The code above never prints "WHILE ENDED" even though it does seem to go out of the while loop when $TEST
>= 10.
但以下代码确实打印了WHILE ENDED":
But the following code does print "WHILE ENDED":
do {
my $qry = $self->getHTMLQuery(undef, $mech->content());
next if (!defined($qry));
push(
@prods,
map { 'http://www.XXXXYYYX.com'.$_->attr('href') }
$qry->query('div.prodInfo div.prodInfoBox a.prodLink.GridItemLink')
);
$qry->delete();
$TEST++;
} while(eval { $mech->follow_link(class => 'jump next') } && $TEST <= 10);
print "WHILE ENDED\n";
在两个测试中,$TEST
的初始值都是0.
In both tests, the initial value of $TEST
is 0.
do...while
中 last
的行为是否不同于 for
和 while {...}?
Is the behavior of
last
in do...while
different than in for
and while {...}
?
推荐答案
带有循环修饰符的
do
块在 next
范围内不算作真正的循环、last
和 redo
是相关的.perlsyn 中提到了这一点,您可以在其中找到 Schwern 提到的关于用裸块围绕它的提示使 last
工作.但这不适用于 next
,因为一个裸块只执行一次,所以 next
的作用类似于 last
.要使 next
工作,您可以将裸块 inside 放在 do
中,但是 last
将像 .
A
do
block with a looping modifier doesn't count as a real loop as far as next
, last
, and redo
are concerned. This is mentioned in perlsyn, where you'll find the tip Schwern mentioned about surrounding it with a bare block to make last
work. But that won't work with next
, because a bare block is only executed once, so next
acts like last
. To make next
work, you can put the bare block inside the do
, but then last
will act like next
.
如果您需要
next
和 last
与 do ... while
一起工作,最简单的方法是使用无限循环在 continue
块中使用真实条件.这两个循环是等效的,除了第二个是真正的循环,因此它与 next
& 一起使用.最后
:
If you need both
next
and last
to work with a do ... while
, the easiest way is to use an infinite loop with the real condition in a continue
block. These 2 loops are equivalent, except that the second is a real loop, so it works with next
& last
:
do { ... } while condition;
while (1) { ... } continue { last unless condition };
这篇关于Perl do...while 和 last 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!