Perl last Statement
Perl last Statement
Perl 中的last 语句类似于 C 中的 break 语句。它在循环中使用立即退出循环。换句话说,最后一个条件迭代循环。
最后一条语句的 Perl 语法如下:
Perl last 语句示例
以下是一个显示 Perl 最后一条语句的简单示例。
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 = <STDIN>;
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 Statement with LABEL
单独使用 Perl last 语句,您只能退出最内层的循环。如果要退出嵌套循环,请在外循环中放置一个标签并将标签传递给最后一个语句。
如果最后一条语句指定了 LABEL,则执行将退出循环,遇到 LABEL 而不是当前封闭循环。
带有 LABEL 的最后一条语句的 Perl 语法如下:
Perl last Statement with LABEL Example
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(<STDIN>){
$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 标签被传递到最后一个语句。