给定perl中的when-continue语句



我在www.perltutorial.org上学习Perl。在那里我知道given-whenswitch-case一样。为了练习,我写了下面的剧本。现在,我知道breakgiven-when中固有的,为了突破这个问题,我需要使用continue语句。

当我给予输入"甜蜜"时,它给予的输出就像"像真人一样"。不应作为输出

"Honey just put your sweet lips on my lipsn
We should just kiss like real people do" 

这是代码:

#!/usr/bin/perl
use strict;
use warnings;
use feature "switch";
my $choice = <STDIN>;
my $msg ="";
chomp($choice);
given(lc $choice){
when('a'){
$msg = "I had a thought, dear";
}
when('b'){
$msg = "However scary";
}
when('c'){
$msg = "About that night";
}
when('d'){
$msg = "The bugs and the dirt";
}
when('e'){
$msg = "Why were you digging?";
}
when('sweet'){
$msg =  "Honey just put your sweet lips on my lips ";
continue;
}
when('lips'){
$msg = $msg."nWe should just kiss like real people do";
}
default{
$msg = "";
}
}
#print($msg,"n");
unless($msg eq "") {
print($msg, "n");
}else{
print("Like real People do!n");
}

请注意,智能匹配功能是实验性的,它被认为是一个破损的设计。扩展而言,交换机功能也是如此,因为它使用智能匹配。这些应该避免。]

实际上,$msg包含空字符串。

#!/usr/bin/perl
use strict;
use warnings;
use feature qw( say switch );
my $choice = "sweetn";
chomp($choice);
my $msg ="";
given(lc $choice){
# ...
when('e'){
$msg = "Why were you digging?";
}
when('sweet'){
$msg = "Honey just put your sweet lips on my lipsn";
continue;
}
when('lips'){
$msg .= "We should just kiss like real people do";
}
default{
$msg = "";
}
}
say ">$msg<";

输出:

given is experimental at a.pl line 8.
when is experimental at a.pl line 10.
when is experimental at a.pl line 14.
when is experimental at a.pl line 17.
><

continue使执行继续到when语句之后的语句。下一个语句是when('lips'){ ... },它什么也不做(因为"sweet" ~~ "lips"是false(。之后的语句是default { $msg = ""; },它清除$msg,因为自我们继续以来没有执行when

要获得所需的结果,您需要以下内容:

given(lc $choice){
# ...
when('e'){
$msg = "Why were you digging?";
}
when('sweet'){
$msg = "Honey just put your sweet lips on my lipsn";
continue;
}
when($_ ~~ 'sweet' || $_ ~~ 'lips'){
$msg .= "We should just kiss like real people do";
}
default{
$msg = "";
}
}

如果没有实验性的开关和智能匹配功能,我们可以使用

for (lc $choice) {
# ...
if ($_ eq 'e'){
$msg = "Why were you digging?";
last;
}
if ($_ eq 'sweet'){
$msg = "Honey just put your sweet lips on my lipsn";
last;
}
if ($_ eq 'sweet' || $_ eq 'lips'){
$msg .= "We should just kiss like real people do";
last;
}
$msg = "";
}

for (lc $choice) {
# ...
if ($_ eq 'e'){
$msg = "Why were you digging?";
}
elsif ($_ eq 'sweet' || $_ eq 'lips'){
if ($_ eq 'sweet'){
$msg = "Honey just put your sweet lips on my lipsn";
}
$msg .= "We should just kiss like real people do";
}
else {
$msg = "";
}
}

最新更新