last: the same to break in C. will jump out of the loop.
- # Print all input lines mentioning fred, until the __END__ marker
-
while (<STDIN>) {
-
if (/__END__/) {
-
# No more input on or after this marker line
-
last;
-
} elsif (/fred/) {
-
print;
-
}
-
}
-
## last comes here #
next: begin a new loop without execute the remained statements. Sometimes you’re not ready for the loop to finish, but you’re done with the current
iteration. That’s what the next operator is good for. It jumps to the inside of the bottom
of the current loop block.‡ After next, control continues with the next iteration of the
loop (much like the “continue” operator in C or a similar language):
- while (<>) {
-
foreach (split) { # break $_ into words, assign each to $_ in turn
-
$total++;
-
next if /\W/; # strange words skip the remainder of the loop
-
$valid++;
-
$count{$_}++; # count each separate word
-
## next comes here ##
-
}
-
}
-
print "total things = $total, valid words = $valid\n";
-
foreach $word (sort keys %count) {
-
print "$word was seen $count{$word} times.\n";
-
}
redo:It says to go back to the top of the
current loop block, without testing any conditional expression or advancing to the next
iteration.
- # Typing test
-
my @words = qw{ fred barney pebbles dino wilma betty };
-
my $errors = 0;
-
foreach (@words) {
-
## redo comes here ##
-
print "Type the word '$_': ";
-
chomp(my $try = <STDIN>);
-
if ($try ne $_) {
-
print "Sorry - That's not right.\n\n";
-
$errors++;
-
redo; # jump back up to the top of the loop
-
}
-
}
-
print "You've completed the test, with $errors errors.\n";
- foreach (1..10) {
-
print "Iteration number $_.\n\n";
-
print "Please choose: last, next, redo, or none of the above? ";
-
chomp(my $choice = <STDIN>);
-
print "\n";
-
last if $choice =~ /last/i;
-
next if $choice =~ /next/i;
-
redo if $choice =~ /redo/i;
-
print "That wasn't any of the choices... onward!\n\n";
-
}
-
print "That's all, folks!\n";
阅读(307) | 评论(0) | 转发(0) |