【问题标题】:How can I run external programs using Perl 6? (e.g. like "system" in Perl 5)如何使用 Perl 6 运行外部程序? (例如,像 Perl 5 中的“系统”)
【发布时间】:2015-04-09 19:40:36
【问题描述】:

我可以在 Perl 5 中使用system 来运行外部程序。我喜欢把system 想象成Perl 中的一个微型“Linux 命令行”。但是,我在 Perl 6 中找不到system 的文档。什么是等效的?

【问题讨论】:

    标签: perl raku


    【解决方案1】:

    Perl6 实际上有两个命令替换 Perl 5 中的 system

    在 Perl6 中,shell 将其参数传递给 shell,类似于 Perl 5 的 system,当它有一个包含元字符的参数时。

    在 Perl6 中,run 试图避免使用 shell。它将第一个参数作为命令,其余参数作为该命令的参数,类似于 Perl 5 的system,当它有多个参数时。

    例如:

    shell('ls > file.log.txt');   # Capture output from ls (shell does all the parsing, etc)
    
    run('ls','-l','-r','-t');     # Run ls with -l, -r, and -t flags
    run('ls','-lrt');             # Ditto
    

    另请参阅2014 Perl 6 Advent post on "running external programs"

    【讨论】:

      【解决方案2】:

      除了使用 shellrun(它们从 Perl 5 替换 system)之外,您还可以使用 NativeCall 来调用 libc 的 system 函数。

      在我的 Windows 机器上,它看起来像这样:

      use NativeCall;
      sub system(Str --> int32) is native("msvcr110.dll") { * };
      system("echo 42");
      

      【讨论】:

      • 那个system和Perl 5版本基本一样吗?
      • 如果你必须指定"msvcr110.dll",我想它不是很便携。你能传递多个参数吗,比如 Perl 5 的system("echo" "42")? (我知道 Windows 不像 Unix 那样处理命令行参数。)
      • @ChristopherBottoms:不,它来自 C 标准库;要获得 Perl5,您需要 Inline::Perl5
      • @KeithThompson: 不,system 需要一个参数 - 在 Windows 上,您需要 _exec family 的函数来避免处理
      • 我一直在寻找shellrun,但提到NativeCall 增加了与操作系统交互的另一个维度,我没有考虑过。因此,我将此标记为已接受的答案。我仍然建议读者也可以查看my answer 以快速了解shellrun 概述和示例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多