Bash的HereDoc中的Perl脚本

Nem*_*emo 19 bash perl

可能有些写在bash脚本定界符一个Perl脚本?

这不起作用(仅限示例)

#/bin/bash
perl <<EOF
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
Run Code Online (Sandbox Code Playgroud)

这里有一些很好的方法如何将perl脚本嵌入到bash脚本中?想从bash脚本运行perl脚本,不要把它放到外部文件中.

Joh*_*ica 23

这里的问题是脚本被传递给stdin上的perl,因此尝试从脚本处理stdin不起作用.

1.字符串文字

perl -e '
while(<>) {
    chomp;
    print "xxx: $_\n";
}
'
Run Code Online (Sandbox Code Playgroud)

使用字符串文字是最直接的写法,但如果Perl脚本本身包含单引号则不理想.

2.使用 perl -e

#/bin/bash

script=$(cat <<'EOF'
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
)
perl -e "$script"
Run Code Online (Sandbox Code Playgroud)

如果你将脚本传递给perl,perl -e那么你将不会遇到stdin问题,你可以在脚本中使用你喜欢的任何字符.不过,要做到这一点有点迂回.Heredocs在stdin上产生输入,我们需要字符串.该怎么办?哦,我知道!这要求$(cat <<HEREDOC).

确保使用<<'EOF'而不仅仅是<<EOF让bash不要在heredoc中进行变量插值.

你也可以在没有$script变量的情况下写这个,尽管它现在变得非常毛茸茸!

perl -e "$(cat <<'EOF'
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
)"
Run Code Online (Sandbox Code Playgroud)

3.流程替代

perl <(cat <<'EOF'
while(<>) {
    chomp;
    print "xxx: $_\n";
}
EOF
)
Run Code Online (Sandbox Code Playgroud)

沿#2行,您可以使用称为进程替换的bash功能,它允许您<(cmd)代替文件名进行写入.如果你使用它,你不需要,-e因为你现在传递perl文件名而不是字符串.