📅  最后修改于: 2021-01-07 08:19:53             🧑  作者: Mango
Perl中的最后一个语句类似于C中的break语句。它在循环内使用,以立即退出循环。换句话说,最后一个条件会循环。
最后一个语句的Perl语法如下:
last;
以下是显示Perl last语句的简单示例。
use warnings;
use strict;
my ($key, $value);
my %rate = ("shoes" => 550,
"boots" => 1200,
"jaggi" => 800,
"jacket" => 1500);
print("Please enter an item to know the price:\n");
$key = ;
chomp($key);
$value = 0;
# searching
foreach(keys %rate){
if($_ eq $key){
$value = $rate{$_};
last; }
}
# result
if($value > 0){
print("$key costs is Rs. $value \n");
}else{
print("$key is not in our list. We apologise!!\n");
}
输出:
Please enter an item to know the price:
boots
boots costs is Rs. 1200
Please enter an item to know the price:
top
top is not in our list. We apologise!!
在上面的程序中
单独使用Perl last语句,您只能退出最内部的循环。如果要退出嵌套循环,请在外部循环中放置一个标签,然后将标签传递给最后一条语句。
如果在最后一条语句中指定了LABEL,则执行会在遇到LABEL的情况下退出循环,而不是当前封闭的循环。
使用LABEL的最后一条语句的Perl语法如下:
last LABEL;
use warnings;
use strict;
my ($key, $value);
my %rate = ("shoes" => 550,
"boots" => 1200,
"jaggi" => 800,
"jacket" => 1500);
$value = 0;
print("Please enter an item to know the price:\n");
OUTER: while(){
$key = $_;
chomp($key);
# searching
INNER: foreach(keys %rate){
if($_ eq $key){
$value = $rate{$_};
last outer;
}
}
print("$key is not in our list. We apologise!!\n") if($value ==0);
# result
}
print("$key costs is Rs. $value \n");
输出:
Please enter an item to know the price:
jaggi
boots costs is Rs. 800
Please enter an item to know the price:
jeans
jeans is not in our list. We apologise!!
上面的程序以相同的方式工作,只是它要求用户在找不到匹配项时再次输入搜索键。
使用了两个标签OUTER和INNER。
在foreach循环中,如果找到匹配项,我们将退出两个循环,因为OUTER标签被传递到了最后一条语句。