如何在Bash脚本中将Bash命令输出传递给多行Perl代码?

use*_*812 1 bash perl pipe

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

Bash command | perl -ne 'single line perl command' | Another Bash command
Run Code Online (Sandbox Code Playgroud)

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

perl -n -e 'command line 1' -e 'command line 2' -e 'command line 3'
Run Code Online (Sandbox Code Playgroud)

或者我可以为多行Perl代码使用"Here Document"(在这种情况下仍然可以指定perl选项,例如"-n").

如果可以使用"Here Document",任何人都可以通过示例说明如何使用它.

提前感谢任何建议.

Jon*_*ler 6

如果您的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
Run Code Online (Sandbox Code Playgroud)

另外,"参阅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
Run Code Online (Sandbox Code Playgroud)

如果脚本比例大于20行(大概在10到50之间,有些根据选择),则可能是时候将Perl脚本分离到自己的文件中并运行它.