|
next 操作符如同 C 语言中 continue ,在 next 之后,程序会继续执行循环的下次迭代。考虑下面例子:
[code=perl]
#!/usr/bin/perl
while (<>) {
chomp($_);
foreach (split) {
$total++;
next if /bad/;
$count{$_}++;
}
}
print "total:$total\n";
print "------------------------------\n";
my @key = keys %count;
my @val = values %count;
foreach (@key) {
print "$_\t";
}
print "\n";
foreach (@val) {
print "$_\t";
}
print "\n";
[/mw_shl_code]
运行输出:# ./next.pl
good well bad great well good bad
total:7
------------------------------
well good great
2 2 1 在上面的程序,while 循环使用 读取命令行参数。这里,命令行参数由 "good well bad great well good bad | " 7 个单词组成,在不指定接收变量的前提下,使用内置变量 $_ 来存放这个命令行。然后,在 foreach 循环里使用 split 函数对这 7 个单词进行分割,在默认情况下,split 是以“空白”作为分隔符的。在 foreach 循环中,遍历每一个单词,如果发现遇到 bad 这个单词,那么将结束本轮迭代,继续扫描下一个单词,如此直到扫描完整个命令行中的所有单词。此外,$count 是一个哈希,每个单词作为其“键”,而该单词的出现次数作为其键值。
和 last 操作符 一样,next 操作符也可以用在 5 种循环块中:for , foreach, while, until 和 裸块。 |
|