perl - 如何在一行中将命令行参数传递给 perl 脚本文件

标签 perl

我有一个在 ubuntu 终端上运行的 perl 脚本文件
所以在运行时,我像这样调用它:

./myscript.pl
在运行时,在终端下,它开始要求我应该进行一些“确认”(用于配置),如下所示:
enter image description here
然后,另一次与另一个要求“确认”
enter image description here
,然后几乎 10 次不同的配置确认
我总是使用默认选项。
所以我的目的是如何能够一次完成,仅在一行命令中,然后能够将它放在 bash_profile 下。
我会试试这个:
./myscript.pl "yes" "yes "no" ..... "yes"
但我不知道这是否可行。

最佳答案

有多种方法可以处理这个问题。如果您控制程序,您应该重新安排它以在它不是交互式时接受默认值(而 IO::Interactive 是一个很好的工具)。
对于非常快的事情,有时我只是偷prompt来自 ExtUtils::MakeMaker .它是独立的,因此您可以根据需要窃取和修改它:

#!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

关于perl - 如何在一行中将命令行参数传递给 perl 脚本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66852044/

相关文章:

Perl 谷歌日历 API

perl - 是否有列出美国邮政编码和州的 CPAN 模块?

Perl -/usr/local/lib64/perl5/Net/SSH2.pm 的散列分配中的奇数个元素

perl - NET::SSH::Expect 配置在 Windows 上工作

javascript - Perl 根据元素 ID 填写表单

perl - 在 Perl 中将 Unicode 数学粗体/斜体字符转换为 latin-1

perl - 在 perl 中发送多部分邮件

Windows - 在 PATH 上找不到文件, '.' 不在 PATH 中

regex - 正则表达式获取一行上的数字

perl - ./script 第 17 行没有这样的文件或目录