如何在输入匹配数组的任何元素之前提示用户?

时间:2017-11-13 18:11:32

标签: perl loops input

我正在写一个Perl程序,我必须提示用户输入,直到输入存在于我之前创建的数组@stops中。如果用户输入匹配,则程序停止提示并将其存储在标量变量$first中。

这不是我的完整代码 - 我的代码中有use strict;use warnings;,而且我之前的代码将值放入数组@stops

print "What is your input?\n";
my $first = <STDIN>;
chomp $first;

do {

    if ( grep { $_ eq $first } @stops ) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        my $first = <STDIN>;
        chomp $first;
    }
}

3 个答案:

答案 0 :(得分:3)

你已经很好了,只有两件事。 a)如果你在else块中使用my $first,你将无法在循环的下一次迭代中检查它。说到循环...... b)do不会在循环中运行,这就是你想要的。

print "What is your input?\n";
my $first = <STDIN>;
chomp $first;
while(1) {
    if (grep { $_ eq $first } @stops) {
        last;
    }
    else {
        print "Invalid stop $first. Enter input again\n";
        $first = <STDIN>;
        chomp $first;
    }
}

如果您已经在某处定义了@stops,那么会这样做。

答案 1 :(得分:0)

我会以通常的方式使用while,其中readline是条件表达式。如果您使用熟悉的习语,它可以帮助人们理解您的代码,这意味着键盘只能在一个地方读取

看起来像这样。请注意,不需要if ... else,因为last仍会退出循环

use strict;
use warnings 'all';
use feature 'say';

my @stops = qw/ a b c /;

my $stop;

print "What is your input? ";

while ( $stop = <STDIN> ) {
    chomp $stop;

    last if grep { $_ eq $stop } @stops;

    print qq{Invalid stop "$stop". Enter input again: };
}

say qq{Found "$stop"};

输出

$perl stop.pl
What is your input? d
Invalid stop "d". Enter input again: x
Invalid stop "x". Enter input again: b
Found "b"

答案 2 :(得分:-1)

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
my $str1="xy";
my $word='';
my @container=();
while($word ne $str1){
  print("Enter: ");
  $word=<STDIN>;
  chomp($word);
  push(@container,$word,', ');
}
print(@container);