gpt4 book ai didi

perl - 重新运行循环迭代

转载 作者:行者123 更新时间:2023-12-04 13:04:28 25 4
gpt4 key购买 nike

我有这个程序,它需要一个单词数组,并要求用户输入一个句子,其中包含数组中的每个单词:

@words = qw(Hi world thanks);
foreach $word (@words)
{
print "Enter a line with word:$word\n";
chomp($input = <STDIN>);
if($input=~/$word/i)
{
print "Great\n";
} else {
print "Incorrect. Type a line containing $word\n";
}
}

如果用户用这个词输入一个输入,它工作正常。但如果他不这样做,它只会打印错误消息并移至下一个单词。我希望它提示用户重新输入同一个单词的输入。但是怎么样?我试了下它没有用。

最佳答案

您可以使用 redo 在这种情况下重新启动当前迭代。

foreach my $word (@words) 
{
print "Enter a line with word:$word\n";
chomp($input = <STDIN>);
if($input=~/$word/i)
{
print "Great\n";
} else {
print "Incorrect. Type a line contaning $word\n";
redo; # restart current iteration.
}
}

一个不太推荐的替代方法是使用 goto :
foreach my $word (@words)
{
INPUT:print "Enter a line with word:$word\n";
chomp($input = <STDIN>);
if($input=~/$word/i)
{
print "Great\n";
} else {
print "Incorrect. Type a line contaning $word\n";
goto INPUT;
}
}

关于perl - 重新运行循环迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510337/

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