【问题标题】:How to pipe Bash command output to multi-line Perl code in a Bash script?如何将 Bash 命令输出通过管道传输到 Bash 脚本中的多行 Perl 代码?
【发布时间】:2012-02-29 11:25:01
【问题描述】:

对于 Bash 脚本中的以下管道:

Bash command | perl -ne 'single line perl command' | Another Bash command

Perl 命令只能是单行。如果我想编写更复杂的多行 Perl 命令怎么样。我可以为每个 perl 命令行使用多个“-e”选项吗,例如:

perl -n -e 'command line 1' -e 'command line 2' -e 'command line 3'

或者我可以为多行 Perl 代码使用“Here Document”吗(在这种情况下应该仍然可以指定 perl 选项,例如“-n”。)?

如果可以使用“Here Document”,谁能举例说明如何使用它。

提前感谢您的任何建议。

【问题讨论】:

    标签: perl bash pipe


    【解决方案1】:

    如果您的 Perl 脚本太长而无法在一行中控制(用分号分隔 Perl 语句),那么bash 很乐意将您的单引号参数扩展到您需要的任意多行:

    Bash-command |
    perl -ne 'print something_here;
              do { something_else } while (0);
              generally("avoid single quotes in your Perl!");
              say q{Here is single-quoted content in Perl};
             ' |
    Another-Bash-Command
    

    'perldoc perlrun' 手册也说:

    -e commandline

    可用于输入一行程序。如果给出-e,Perl 将不会在参数列表中查找文件名。可以给出多个-e 命令来构建多行脚本。确保在正常程序中使用分号。

    -E commandline

    行为与 -e 类似,只是它隐式启用所有可选功能(在主编译单元中)。

    所以你也可以这样做:

    Bash-command |
    perl -n -e 'print something_here;' \
            -e 'do { something_else } while (0);' \
            -e 'generally("avoid single quotes in your Perl!");' \
            -e 'say q{Here is single-quoted content in Perl};' |
    Another-Bash-Command
    

    如果脚本变得大于 20 行(介于 10 到 50 之间,取决于选择),那么可能是时候将 Perl 脚本分离到自己的文件中并运行它了。

    【讨论】:

      【解决方案2】:

      对于多行 Perl,您只需用分号分隔命令,而不是传递多个 -e 调用。例如:

      perl -n -e 'command line 1; command line 2;'
      

      (虽然我通常不会说 Perl 块本身就是“命令行”)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        • 1970-01-01
        • 2023-01-26
        • 2021-05-20
        • 2016-09-20
        • 2015-03-01
        • 1970-01-01
        相关资源
        最近更新 更多