gpt4 book ai didi

perl - Perl 中的 Given-when-continue 语句

转载 作者:行者123 更新时间:2023-12-02 07:57:47 25 4
gpt4 key购买 nike

我是从 www.perltutorial.org 学习 Perl 的.在那里我了解到 given-when 就像 switch-case。因此为了练习我写了下面的脚本。现在我开始知道 breakgiven-when 中固有的,为了成功,我需要使用 continue 语句。

当我给出“甜蜜”的输入时,它给出的输出是“像真人一样”。不应该输出为

"Honey just put your sweet lips on my lips\n
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 = "sweet\n";
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 lips\n";
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 lips\n";
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 lips\n";
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 lips\n";
}

$msg .= "We should just kiss like real people do";
}
else {
$msg = "";
}
}

关于perl - Perl 中的 Given-when-continue 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61352716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com