有多种方法可以处理这个问题。如果您控制程序,您应该重新安排它以在它不是交互式时接受默认值(IO::Interactive 是一个很好的工具)。
对于真正快速的事情,有时我只是从ExtUtils::MakeMaker 窃取prompt。它是独立的,因此您可以根据需要窃取和修改它:
#!perl
use v5.10;
use ExtUtils::MakeMaker qw(prompt);
my @answers;
push @answers, prompt( "First", "yes" );
push @answers, prompt( "Second", "yes" );
push @answers, prompt( "Third", "yes" );
say "Done! Got @answers";
如果我正常运行,我必须回答提示:
$ perl yes.pl
First [yes] cat
Second [yes] dog
Third [yes] bird
Done! Got cat dog bird
但是ExtUtils::MakeMaker 有一个环境变量可以接受默认值:
$ PERL_MM_USE_DEFAULT=1 perl yes.pl
First [yes] yes
Second [yes] yes
Third [yes] yes
Done! Got yes yes yes
从这里到答案的结尾只是提供输入的 shell 技术。没有特殊的 Perl 东西在发生。而且,根据程序本身试图做的事情,有些事情可能无法正常工作。
我也可以喂它/dev/null,在这种情况下,它会意识到程序没有以交互方式运行,并且它接受我的默认值:
$ perl yes.pl < /dev/null
First [yes] yes
Second [yes] yes
Third [yes] yes
Done! Got yes yes yes
但是,我也可以输入一个多行字符串:
$ perl yes.pl <<HERE
yes
yes
no
HERE
First [yes] Second [yes] Third [yes] Done! Got yes yes no
这对你的文件来说可能太多了,所以你可以用嵌入的行来回显一个字符串:
$ perl yes.pl < <( echo -e "yes\nno\nhello")
First [yes] Second [yes] Third [yes] Done! Got yes no hello
$ perl yes.pl < <( echo $'yes\nno\nhello')
First [yes] Second [yes] Third [yes] Done! Got yes no hello
或者从文件中获取输入:
$ perl yes.pl < input.txt
First [yes] Second [yes] Third [yes] Done! Got heck yeah no way yep
而且,从simbabque's answer 偷来的,因为我要列出技术列表:
$ printf "yes\nyes\nno\n...\nyes\n" | yes.pl