【问题标题】:Get an input of array using Getoptions in perl在 perl 中使用 Getoptions 获取数组的输入
【发布时间】:2014-11-12 22:19:21
【问题描述】:

我正在尝试使用 Getoptions 在 perl 中创建一个文件,其中一个输入是一个数组。我的代码如下所示:

my $filename = 'grid.sh';
my @job_name;
my $output_file;
my $testbench;
my %opts = (
 'job_name' => \@job_name,
 'output' => \$output_file,
 'testbench' => \$testbench,
);
GetOptions(
  \%opts,
 'job_name=s',
'output=s',
'testbench=s'
);
open(my $fh, '>', $filename) or die "Could not open";
for (my $i=0; $i <= 2; $i++) {
print $fh "Job names are $job_name[$i]";
}
   close $fh;

在我的命令行中,我将输入提供为

perl grip_script.pl "-job_name test -job_name test1 -job_name test2"

但是文件没有提供正确的数据。你能告诉我哪里出错了吗?

谢谢

【问题讨论】:

  • '不匹配的右花括号'是复制/粘贴错误?我猜你正在使用 GetOpt::Long。
  • 你很抱歉。这是一个复制/粘贴错误。是的,我正在使用 GetOpt::Long

标签: perl getopt


【解决方案1】:

您错误地双引号引用了整个参数列表,从而使其成为单个无效参数。

试试这个:

perl grip_script.pl --job_name test --job_name test1 --job_name test2

正如 bytepusher 建议的那样,您还需要修复对 GetOptions 的调用:

GetOptions(
 'job_name=s' => \@job_name,
 'output' => \$output_file,
 'testbench' => \$testbench,
);

通过这两项更改,我能够运行您的测试脚本并获得预期的结果。

输出:

Job names are testJob names are test1Job names are test2

请注意,您的打印语句中缺少换行符,因此所有三个打印调用都出现在同一行。

【讨论】:

    【解决方案2】:

    您对 GetOpts 的表示法让我感到困惑。

    你为什么要传入 %opts 然后更多?

    你试过了吗?

    GetOptions(
        'job_name=s' => \@job_name,
    'output=s' => \$output_file,
    'testbench=s' => \$testbench,
    );
    

    ?

    另外,请参阅documentation 中传入的多个值的更多示例。

    这些值只有在你不在命令行中引用时才会出现,正如其他回答者指出的那样,所以调用

    perl grip_script.pl --job_name test --job_name test2 --job_name test3
    

    对我来说,他们都在@job_name 中。

    【讨论】:

    • 当我使用你们都提到的例子时,只有我的第一份“测试”工作出现了。其他两个 test1 和 test2 不是问题所在。
    • 嗯。玩了一会儿后才注意到自己。让我回复你;)
    • 先生。 Sam Choukri 说得对,我的符号和没有引号,两者都在我的 @job_name 中。
    • 嘿伙计们,我现在开始工作了。你的意见帮助了我。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 2014-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多