I have this program which takes a array of words and asks user to type a sentence which has each of the word 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 types a input with the word, it works fine. But if he doesn't It only prints the error message and moves to the next word. I want it it prompt the user to re-enter inputs for the same word. But how ? I tried next it did not work.
You can use a redo
in this case to 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 a 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;
}
}
I would create an infinite while
loop to exit out of:
#!/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";
}
}
}
of course I would probably separate the logic of each individual word into a sub, then loop over that:
#!/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";
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With