1

How to pass file to perl script for processing and also use heredoc syntax for multi-line perl script? 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
1
  • All you need is perl -ple'$_="\t$_"if!/\t/' (if @F!=2 when @F<2, and if the input is specifically tab separated rather than whitespace separated) Commented Apr 23, 2013 at 1:55

3 Answers 3

3

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.


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
Sign up to request clarification or add additional context in comments.

3 Comments

I assume cat ng.input in the question is just a placeholder for some other process that will pipe input to the script. Otherwise there wouldn't be a problem using the here-doc.
@Barmar, That's completely besides the point. A multi-line argument can also be used with ... | perl. (But to address your comment anyway, you underestimate how many people use cat file |.)
That's why there's a UUOC award, though in actuality, it is hard to find a novel UUOC — they're mainly mundane repetitions of the same old problem, over and over.
1

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.

1 Comment

@JonathanLeffler Thanks, I didn't even notice the -e in the original question.
0

Can also pass a heredoc as a "-" first argument to perl:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.