简体   繁体   English

使用来自 bash 的 stdin 的多行 perl 的 heredoc 语法

[英]heredoc syntax for multi-line perl using stdin from bash

How to pass file to perl script for processing and also use heredoc syntax for multi-line perl script?如何将文件传递给 perl 脚本进行处理,并对多行 perl 脚本使用 heredoc 语法? I have tried those but no luck:我试过这些,但没有运气:

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

There's really no need for here-docs. 确实不需要这里的文档。 You could simply use a multi-line argument: 您可以简单地使用多行参数:

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

Clean, more portable than Barmar's, and only uses one process instead of Barmar's three. 清洁,比Barmar的便携式,并且仅使用一个过程而不是Barmar的三个过程。


Note that your code could be shrunk to 请注意,您的代码可能会缩小为

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

or even 甚至

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

Use process substitution: 使用流程替代:

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

Also put single quotes around the EOF tag so that $F in the perl script won't be expanded as shell variables. 还要在EOF标记EOF加上单引号,以使perl脚本中的$F不会被扩展为shell变量。

Can also pass a heredoc as a "-" first argument to perl:也可以将heredoc 作为“-”第一个参数传递给perl:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM