Repeat the loop

I have this program that takes an array of words and asks the user to type a sentence containing each of the words from the array:

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

If the user enters input with the word, it works fine. But if he does not, he prints an error message and moves on to the next word. I want it to prompt the user to re-enter the input for the same word. But how? I tried, then it didn’t work.

+5
source share
3 answers

In this case, you can use redoto restart the current iteration.

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.
        }
}

A less recommended alternative is to use 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;
        }
}
+18
source

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";
    }
  }
}
+3

While redodefinitely a cuter, here's the c version while ... continue. It relies on an inner loop that only goes out when you enter the correct word and prints a correction for each incorrect answer.

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

Please note that chompin this case is not required.

+3
source

All Articles