【问题标题】:Can I obtain values from a perl script using a system call from the middle of another perl script?我可以使用来自另一个 perl 脚本中间的系统调用从 perl 脚本中获取值吗?
【发布时间】:2012-01-24 15:09:01
【问题描述】:

我正在尝试修改其他人编写的脚本,并且我想将我的脚本与他的脚本分开。

我编写的脚本以print 行结尾,输出所有相关数据,以空格分隔。

例如:print "$sap $stuff $more_stuff";

我想在另一个 perl 脚本的中间使用这些数据,但我不确定是否可以对我编写的脚本使用系统调用。

例如:system("./sap_calc.pl $id"); #obtain printed data from sap_calc.pl here

这可以吗?如果没有,我该怎么做?


有些相关,但不使用system():

How can I get one Perl script to see variables in another Perl script?

How can I pass arguments from one Perl script to another?

【问题讨论】:

  • 阅读您正在使用的函数的文档! “perldoc -f system”在第 3 段中回答了您的问题“您想使用什么来捕获命令的输出,因为您应该只使用......”

标签: perl arguments parameter-passing stdout stdin


【解决方案1】:

您正在寻找“反引号运算符”。

查看perlop,“类似引用的运算符”部分。

通常,捕获程序的输出是这样的:

my $output = `/bin/cmd ...`;

请注意,反引号运算符仅捕获 STDOUT。因此,为了捕获所有内容(也包括 STDERR),命令需要附加通常的 shell 重定向“2>&1”。

【讨论】:

  • 我执行了那个替换。谢谢,@ephemient
  • 如果您需要了解 STDERR,还有 open3。
【解决方案2】:

如果你想使用从其他脚本打印到标准输出的数据,你需要使用backticks or qx()。

system 只会返回 shell 命令的返回值,而不是实际的输出。

虽然执行此操作的正确方法是将实际代码导入到您的其他脚本中,但通过构建module 或简单地使用do。

作为一般规则,最好使用所有 perl 解决方案,而不是依赖 system/shell 作为一种“简化”方式。

我的文件.pl:

sub foo {
    print "Foo";
}
1;

main.pl:

do 'myfile.pl';
foo();

【讨论】:

    【解决方案3】:

    perldoc perlipc

    反引号,就像在 shell 中一样,会将命令的标准输出作为字符串(或数组,取决于上下文)产生。它们可以更清楚地写成类似引号的qx 运算符。

    @lines = `./sap_calc.pl $id`;
    @lines = qx(./sap_calc.pl $id);
    $all = `./sap_calc.pl $id`;
    $all = qx(./sap_calc.pl $id);
    

    open 也可以用于流式传输,而不是一次全部读入内存(就像qx 所做的那样)。这也可以绕过shell,从而避免各种引用问题。

    open my $fh, '-|', './sap_calc.pl', $id;
    while (readline $fh) {
        print "read line: $_";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2012-12-17
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      相关资源
      最近更新 更多