【问题标题】:perl calling another perl script with options/switchesperl 使用选项/开关调用另一个 perl 脚本
【发布时间】:2018-07-21 00:01:43
【问题描述】:

我有一个主 Perl 脚本,它需要使用选项调用另一个 Perl 脚本。我阅读了很多关于参数的线程,但我需要参数和选项。以下是我的示例代码:

sub run_script_a{
   my $script_path = "/home/sample/script.pl"
   my @ARGS = "input.txt";

   ##I need to capture the result of the script run and fail if something went wrong
   system($^X, $tool_path, @ARGS);
}

我尝试了以下方法:

my @ARGS = "input.txt -o output.txt";

它不起作用,给了我这个错误:

Cannot open input.txt -o output.txt for read: No such file or directory

如何让它发挥作用?第二个脚本运行为:

sample.pl input.txt -o output.txt

我不擅长编写 bash 脚本,所以我使用 Perl。

【问题讨论】:

  • 我也试过这个:我的@ARGS = ("input.txt", "-o ", "output.txt");。我得到的错误是:“未知选项:o”即使我发送“--o”,“-”也会被忽略
  • 删除“-o”中的尾随空格。如果您使用列表作为 system 的参数,它不会通过 shell,这意味着不会忽略多余的空格。
  • 删除尾随空格修复了它!谢谢!

标签: perl


【解决方案1】:
my $tool_path = "/home/sample/script.pl"
my @args = "input.txt -o output.txt";
system($tool_path, @args);

相当于shell命令

/home/sample/script.pl "input.txt -o output.txt"

你想要

my $tool_path = "/home/sample/script.pl"
my @args = ( "input.txt", "-o", "output.txt" );
system($tool_path, @args);

实际上,如果要捕获输出,则无需涉及文件。你想要的

use IPC::System::Simple qw( capturex );

my $tool_path = "/home/sample/script.pl"
my @args = "input.txt";
my $output = capturex($tool_path, @args);

【讨论】:

    【解决方案2】:

    使用反引号运行带有参数的脚本并捕获输出 (perldoc -f qx)。

    perl -E'say `echo 4 | $^X -p ./script.pl`'
    

    script.pl 的内容:

    $_**=3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-17
      • 2012-03-10
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多