如何将命令行参数单行传递给 perl 脚本文件

how to pass command line arguments to perl script file in one-line

我有一个 perl 脚本文件,它在 ubuntu 终端

上运行

所以当 运行 时,我是这样调用它的:

./myscript.pl

而 运行,在终端下,它开始要求我应该录音的一些“确认”(用于配置),如下所示:

然后,另一次与另一个要求“确认”

,然后将近 10 次用于不同的配置确认 我总是点击默认选项。

所以我的目的是如何能够一次性完成,仅在一行命令中,然后能够将其放在 bash_profile.

我会试试这个:

./myscript.pl "yes" "yes "no" ..... "yes"

但我不知道这样行不行。

这完全取决于你的程序是如何编写的。我怀疑它看起来像这样:

#!/usr/bin/perl

use strict;
use warnings;

my $default = 'yes';
print "Do you want to proceed with this installation? [$default] ";
chomp( my $answer = <STDIN> );

$answer = $default unless length $answer;

print "You said $answer\n";

在这种情况下,您可以使用如下代码在命令行上传递默认值:

#!/usr/bin/perl

use strict;
use warnings;

my $default = 'yes';
my $answer;

if (@ARGV) {
  $answer = shift;
} else {
  print "Do you want to proceed with this installation? [$default] ";
  chomp( $answer = <STDIN> );
}

$answer = $default unless length $answer;

print "You said $answer\n";

您需要对每个单独的提示重复这些更改。

您可以使用 printf on the commandline 将多行输入通过管道传输到您的程序中。如果它期望 yesno 之类的东西按固定顺序排列,那应该就足够了。

$ printf "yes\nyes\nno\n...\nyes\n" | ./myscript.pl

有关详细信息,请参阅 this blog post

有多种方法可以解决这个问题。如果您控制该程序,您应该重新安排它在非交互时接受默认值(IO::Interactive 是一个很好的工具)。

对于非常快的事情,有时我只是从 ExtUtils::MakeMakerprompt。它是独立的,因此您可以根据需要窃取和修改它:

#!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,在这种情况下它会意识到程序不是 运行ning 交互,它接受我的默认值:

$ 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

而且,从 偷来的,因为我要获取技术列表:

$ printf "yes\nyes\nno\n...\nyes\n" | yes.pl