使用bash中的stdin进行多行perl的heredoc语法

时间:2013-04-23 00:07:11

标签: perl bash stdin heredoc

如何将文件传递给perl脚本进行处理,并使用heredoc语法进行多行perl脚本?我尝试过这些但没有运气:

cat ng.input | perl -nae <<EOF
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF

cat ng.input | perl -nae - <<EOF
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF

2 个答案:

答案 0 :(得分:3)

这里的文档确实没有必要。您可以简单地使用多行参数:

perl -nae'
    if (@F==2) {
       print $F[0] . "\t". $F[1] . "\n"
    } else {
       print "\t" . $F[0] . "\n"
    }
' ng.input

清洁,比Barmar更便携,只使用一个过程而不是Barmar的三个过程。


请注意,您的代码可以缩小为

perl -lane'unshift @F, "" if @F!=2; print "$F[0]\t$F[1]";' ng.input

甚至

perl -pale'unshift @F, "" if @F!=2; $_="$F[0]\t$F[1]";' ng.input

答案 1 :(得分:1)

使用流程替换:

cat ng.input | perl -na <(cat <<'EOF'
if (@F==2) {print $F[0] . "\t". $F[1] . "\n"} else { print "\t" . $F[0] . "\n" }
EOF
)

还在EOF标记周围放置单引号,以便perl脚本中的$F不会作为shell变量展开。

相关问题