加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 重新运行循环迭代

发布时间:2020-12-15 23:35:51 所属栏目:大数据 来源:网络整理
导读:我有这个程序,它取一个单词的数组,并要求用户输入一个句子,其中包含数组中的每个单词: @words = qw(Hi world thanks);foreach $word (@words) { print "Enter a line with word:$wordn"; chomp($input = STDIN); if($input=~/$word/i) { print "Greatn";
我有这个程序,它取一个单词的数组,并要求用户输入一个句子,其中包含数组中的每个单词:

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

如果用户使用单词键入输入,则可以正常工作.但如果他不这样做它只打印错误信息并移动到下一个单词.我希望它提示用户重新输入相同单词的输入.但是怎么样?我接下来尝试了它没有用.

解决方法

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

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

不太推荐的替代方案是使用goto

foreach my $word (@words)
{
        INPUT:print "Enter a line with word:$wordn";
        chomp($input = <STDIN>);
        if($input=~/$word/i)
        {
                print "Greatn";
        } else {
                print "Incorrect. Type a line contaning $wordn";
                goto INPUT;
        }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读