在C语言中,如果想要退出一个循环,我们可以使用break。在perl中,没有beak这个关键字,但是perl却也提供了另外一个关键字,让程序从循环中跳出,那就是last。现在我们就看一下last的使用。
#! /usr/bin/perl
use strict;
use warnings;
my @array = (1 .. 100);
foreach my $elem (@array)
{
print "$elem\t";
last if($elem / 3 == 0)
}
print "\nHello!\n";
上面的程序,在foreach中,只会打印三个数字1,2,3就退出了,就好比执行时遇到break一样。
注意:last不能用于具有返回值得模块当中,例如子程序。
下面是perl上对last用法的注意提示:
last cannot be used to exit a block that returns a value such as eval {} , sub {} , or do {} , and should not be used to exit a grep() or map() operation.
Note that a block by itself is semantically identical to a loop that executes once. Thus last can be used to effect an early exit out of such a block.
转自:http://www.perlcn.com/perlbc/perljc/203.html