重新运行循环迭代

时间:2011-12-14 19:16:15

标签: perl loops

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

@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";
        }
}

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

3 个答案:

答案 0 :(得分:18)

在这种情况下,您可以使用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;
        }
}

答案 1 :(得分:3)

我会创建一个无限while循环退出:

#!/usr/bin/env perl

use strict;
use warnings;

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

当然我可能会将每个单词的逻辑分成一个子,然后循环:

#!/usr/bin/env perl

use strict;
use warnings;

my @words = qw(Hi world thanks);
get_word($_) for @words;

sub get_word {
  my $word = shift or die "Need a word";
  print "Enter a line with word: $word\n";
  while (1) {
    chomp( my $input = <STDIN> );
    if( $input=~/$word/i )  {
      print "Great\n";
      last;
    } else {
      print "Incorrect. Type a line contaning $word\n";
    }
  }
}

答案 2 :(得分:3)

虽然redo绝对是可爱的,但这是一个while ... continue的版本。它依赖于仅在输入正确单词时退出的内循环,并为每个错误答案打印校正。

use strict;
use warnings;

my @words = qw(Hi world thanks);
foreach my $word (@words) {
    print "Enter a line with word: $word\n";
    while (my $input = <>) {
        last if $input =~ /$word/;
    } continue {
        print "Incorrect. Type a line contaning $word\n";
    }
    print "Great\n";
}

请注意,在这种情况下不需要chomp